fix deprecations: use choices_as_values=true and flip content of the choice options

This commit is contained in:
nobohan 2018-04-04 17:54:17 +02:00
parent 95f32a8fcb
commit 4143e773b6
2 changed files with 72 additions and 70 deletions

View File

@ -44,39 +44,39 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
*/ */
class ListActivity implements ListInterface class ListActivity implements ListInterface
{ {
/** /**
* *
* @var EntityManagerInterface * @var EntityManagerInterface
*/ */
protected $entityManager; protected $entityManager;
/** /**
* *
* @var TranslatorInterface * @var TranslatorInterface
*/ */
protected $translator; protected $translator;
/** /**
* *
* @var TranslatableStringHelper * @var TranslatableStringHelper
*/ */
protected $translatableStringHelper; protected $translatableStringHelper;
protected $fields = array( protected $fields = array(
'id', 'id',
'date', 'date',
'durationTime', 'durationTime',
'attendee', 'attendee',
'list_reasons', 'list_reasons',
'user_username', 'user_username',
'circle_name', 'circle_name',
'type_name', 'type_name',
'person_firstname', 'person_firstname',
'person_lastname', 'person_lastname',
'person_id' 'person_id'
); );
public function __construct( public function __construct(
EntityManagerInterface $em, EntityManagerInterface $em,
TranslatorInterface $translator, TranslatorInterface $translator,
@ -87,10 +87,10 @@ class ListActivity implements ListInterface
$this->translator = $translator; $this->translator = $translator;
$this->translatableStringHelper = $translatableStringHelper; $this->translatableStringHelper = $translatableStringHelper;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
* *
* @param FormBuilderInterface $builder * @param FormBuilderInterface $builder
*/ */
public function buildForm(FormBuilderInterface $builder) public function buildForm(FormBuilderInterface $builder)
@ -99,6 +99,7 @@ class ListActivity implements ListInterface
'multiple' => true, 'multiple' => true,
'expanded' => true, 'expanded' => true,
'choices' => array_combine($this->fields, $this->fields), 'choices' => array_combine($this->fields, $this->fields),
'choices_as_values' => true,
'label' => 'Fields to include in export', 'label' => 'Fields to include in export',
'constraints' => [new Callback(array( 'constraints' => [new Callback(array(
'callback' => function($selected, ExecutionContextInterface $context) { 'callback' => function($selected, ExecutionContextInterface $context) {
@ -115,7 +116,7 @@ class ListActivity implements ListInterface
/** /**
* {@inheritDoc} * {@inheritDoc}
* *
* @return type * @return type
*/ */
public function getAllowedFormattersTypes() public function getAllowedFormattersTypes()
@ -130,35 +131,35 @@ class ListActivity implements ListInterface
public function getLabels($key, array $values, $data) public function getLabels($key, array $values, $data)
{ {
switch ($key) switch ($key)
{ {
case 'date' : case 'date' :
return function($value) { return function($value) {
if ($value === '_header') return 'date'; if ($value === '_header') return 'date';
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $value); $date = \DateTime::createFromFormat('Y-m-d H:i:s', $value);
return $date->format('d-m-Y'); return $date->format('d-m-Y');
}; };
case 'attendee': case 'attendee':
return function($value) { return function($value) {
if ($value === '_header') return 'attendee'; if ($value === '_header') return 'attendee';
return $value ? 1 : 0; return $value ? 1 : 0;
}; };
case 'list_reasons' : case 'list_reasons' :
/* @var $activityReasonsRepository EntityRepository */ /* @var $activityReasonsRepository EntityRepository */
$activityRepository = $this->entityManager $activityRepository = $this->entityManager
->getRepository('ChillActivityBundle:Activity'); ->getRepository('ChillActivityBundle:Activity');
return function($value) use ($activityRepository) { return function($value) use ($activityRepository) {
if ($value === '_header') return 'activity reasons'; if ($value === '_header') return 'activity reasons';
$activity = $activityRepository $activity = $activityRepository
->find($value); ->find($value);
return implode(", ", array_map(function(ActivityReason $r) { return implode(", ", array_map(function(ActivityReason $r) {
return '"'. return '"'.
$this->translatableStringHelper->localize($r->getCategory()->getName()) $this->translatableStringHelper->localize($r->getCategory()->getName())
.' > '. .' > '.
@ -169,21 +170,21 @@ class ListActivity implements ListInterface
case 'circle_name' : case 'circle_name' :
return function($value) { return function($value) {
if ($value === '_header') return 'circle'; if ($value === '_header') return 'circle';
return $this->translatableStringHelper return $this->translatableStringHelper
->localize(json_decode($value, true)); ->localize(json_decode($value, true));
}; };
case 'type_name' : case 'type_name' :
return function($value) { return function($value) {
if ($value === '_header') return 'activity type'; if ($value === '_header') return 'activity type';
return $this->translatableStringHelper return $this->translatableStringHelper
->localize(json_decode($value, true)); ->localize(json_decode($value, true));
}; };
default: default:
return function($value) use ($key) { return function($value) use ($key) {
if ($value === '_header') return $key; if ($value === '_header') return $key;
return $value; return $value;
}; };
} }
@ -212,15 +213,15 @@ class ListActivity implements ListInterface
public function initiateQuery(array $requiredModifiers, array $acl, array $data = array()) public function initiateQuery(array $requiredModifiers, array $acl, array $data = array())
{ {
$centers = array_map(function($el) { return $el['center']; }, $acl); $centers = array_map(function($el) { return $el['center']; }, $acl);
// throw an error if any fields are present // throw an error if any fields are present
if (!\array_key_exists('fields', $data)) { if (!\array_key_exists('fields', $data)) {
throw new \Doctrine\DBAL\Exception\InvalidArgumentException("any fields " throw new \Doctrine\DBAL\Exception\InvalidArgumentException("any fields "
. "have been checked"); . "have been checked");
} }
$qb = $this->entityManager->createQueryBuilder(); $qb = $this->entityManager->createQueryBuilder();
$qb $qb
->from('ChillActivityBundle:Activity', 'activity') ->from('ChillActivityBundle:Activity', 'activity')
->join('activity.person', 'person') ->join('activity.person', 'person')
@ -228,7 +229,7 @@ class ListActivity implements ListInterface
->andWhere('center IN (:authorized_centers)') ->andWhere('center IN (:authorized_centers)')
->setParameter('authorized_centers', $centers); ->setParameter('authorized_centers', $centers);
; ;
foreach ($this->fields as $f) { foreach ($this->fields as $f) {
if (in_array($f, $data['fields'])) { if (in_array($f, $data['fields'])) {
switch ($f) { switch ($f) {
@ -265,12 +266,12 @@ class ListActivity implements ListInterface
$qb->addSelect(sprintf('activity.%s as %s', $f, $f)); $qb->addSelect(sprintf('activity.%s as %s', $f, $f));
break; break;
} }
} }
} }
return $qb; return $qb;
} }

View File

@ -21,42 +21,42 @@ use Chill\ActivityBundle\Form\Type\TranslatableActivityReason;
class ActivityType extends AbstractType class ActivityType extends AbstractType
{ {
use AppendScopeChoiceTypeTrait; use AppendScopeChoiceTypeTrait;
/** /**
* the user running this form * the user running this form
* *
* @var User * @var User
*/ */
protected $user; protected $user;
/** /**
* *
* @var AuthorizationHelper * @var AuthorizationHelper
*/ */
protected $authorizationHelper; protected $authorizationHelper;
/** /**
* *
* @var ObjectManager * @var ObjectManager
*/ */
protected $om; protected $om;
/** /**
* *
* @var TranslatableStringHelper * @var TranslatableStringHelper
*/ */
protected $translatableStringHelper; protected $translatableStringHelper;
protected $timeChoices; protected $timeChoices;
public function __construct( public function __construct(
TokenStorageInterface $tokenStorage, TokenStorageInterface $tokenStorage,
AuthorizationHelper $authorizationHelper, ObjectManager $om, AuthorizationHelper $authorizationHelper, ObjectManager $om,
TranslatableStringHelper $translatableStringHelper, TranslatableStringHelper $translatableStringHelper,
array $timeChoices array $timeChoices
) )
{ {
if (!$tokenStorage->getToken()->getUser() instanceof User) { if (!$tokenStorage->getToken()->getUser() instanceof User) {
throw new \RuntimeException("you should have a valid user"); throw new \RuntimeException("you should have a valid user");
@ -67,7 +67,7 @@ class ActivityType extends AbstractType
$this->translatableStringHelper = $translatableStringHelper; $this->translatableStringHelper = $translatableStringHelper;
$this->timeChoices = $timeChoices; $this->timeChoices = $timeChoices;
} }
/** /**
* @param FormBuilderInterface $builder * @param FormBuilderInterface $builder
* @param array $options * @param array $options
@ -76,35 +76,36 @@ class ActivityType extends AbstractType
{ {
// handle times choices // handle times choices
$timeChoices = array(); $timeChoices = array();
foreach ($this->timeChoices as $e) { foreach ($this->timeChoices as $e) {
$timeChoices[$e['label']] = $e['seconds']; $timeChoices[$e['label']] = $e['seconds'];
}; };
$durationTimeTransformer = new DateTimeToTimestampTransformer('GMT', 'GMT'); $durationTimeTransformer = new DateTimeToTimestampTransformer('GMT', 'GMT');
$durationTimeOptions = array( $durationTimeOptions = array(
'choices' => $timeChoices, 'choices' => $timeChoices,
'choices_as_values' => true, 'choices_as_values' => true,
'placeholder' => 'Choose the duration', 'placeholder' => 'Choose the duration',
); );
$builder $builder
->add('date', 'date', array( ->add('date', 'date', array(
'required' => true, 'required' => true,
'widget' => 'single_text', 'widget' => 'single_text',
'format' => 'dd-MM-yyyy') 'format' => 'dd-MM-yyyy')
) )
->add('durationTime', ChoiceType::class, $durationTimeOptions) ->add('durationTime', ChoiceType::class, $durationTimeOptions)
->add('remark', 'textarea', array( ->add('remark', 'textarea', array(
'required' => false, 'required' => false,
'empty_data' => '' 'empty_data' => ''
)) ))
->add('attendee', ChoiceType::class, array( ->add('attendee', ChoiceType::class, array(
'expanded' => true, 'expanded' => true,
'required' => false, 'required' => false,
'choices_as_values' => true,
'choices' => array( 'choices' => array(
true => 'present', 'present' => true,
false => 'not present' 'not present' => false
) )
)) ))
->add('user') ->add('user')
@ -118,44 +119,44 @@ class ActivityType extends AbstractType
'active_only' => true 'active_only' => true
)) ))
; ;
$this->appendScopeChoices($builder, $options['role'], $this->appendScopeChoices($builder, $options['role'],
$options['center'], $this->user, $this->authorizationHelper, $options['center'], $this->user, $this->authorizationHelper,
$this->translatableStringHelper, $this->om); $this->translatableStringHelper, $this->om);
$builder->get('durationTime') $builder->get('durationTime')
->addModelTransformer($durationTimeTransformer); ->addModelTransformer($durationTimeTransformer);
$builder->get('durationTime') $builder->get('durationTime')
->addEventListener( ->addEventListener(
FormEvents::PRE_SET_DATA, FormEvents::PRE_SET_DATA,
function(FormEvent $formEvent) use ( function(FormEvent $formEvent) use (
$timeChoices, $timeChoices,
$builder, $builder,
$durationTimeTransformer, $durationTimeTransformer,
$durationTimeOptions $durationTimeOptions
) )
{ {
// set the timezone to GMT, and fix the difference between current and GMT // set the timezone to GMT, and fix the difference between current and GMT
// the datetimetransformer will then handle timezone as GMT // the datetimetransformer will then handle timezone as GMT
$timezoneUTC = new \DateTimeZone('GMT'); $timezoneUTC = new \DateTimeZone('GMT');
/* @var $data \DateTime */ /* @var $data \DateTime */
$data = $formEvent->getData() === NULL ? $data = $formEvent->getData() === NULL ?
\DateTime::createFromFormat('U', 300) : \DateTime::createFromFormat('U', 300) :
$formEvent->getData(); $formEvent->getData();
$seconds = $data->getTimezone()->getOffset($data); $seconds = $data->getTimezone()->getOffset($data);
$data->setTimeZone($timezoneUTC); $data->setTimeZone($timezoneUTC);
$data->add(new \DateInterval('PT'.$seconds.'S')); $data->add(new \DateInterval('PT'.$seconds.'S'));
// test if the timestamp is in the choices. // test if the timestamp is in the choices.
// If not, recreate the field with the new timestamp // If not, recreate the field with the new timestamp
if (!in_array($data->getTimestamp(), $timeChoices)) { if (!in_array($data->getTimestamp(), $timeChoices)) {
// the data are not in the possible values. add them // the data are not in the possible values. add them
$timeChoices[$data->format('H:i')] = $data->getTimestamp(); $timeChoices[$data->format('H:i')] = $data->getTimestamp();
$form = $builder->create( $form = $builder->create(
'durationTime', 'durationTime',
ChoiceType::class, ChoiceType::class,
array_merge( array_merge(
$durationTimeOptions, $durationTimeOptions,
array( array(
@ -168,7 +169,7 @@ class ActivityType extends AbstractType
} }
}); });
} }
/** /**
* @param OptionsResolverInterface $resolver * @param OptionsResolverInterface $resolver
*/ */
@ -177,7 +178,7 @@ class ActivityType extends AbstractType
$resolver->setDefaults(array( $resolver->setDefaults(array(
'data_class' => 'Chill\ActivityBundle\Entity\Activity' 'data_class' => 'Chill\ActivityBundle\Entity\Activity'
)); ));
$this->appendScopeChoicesOptions($resolver); $this->appendScopeChoicesOptions($resolver);
} }