0
votes

Here is some form I create :

$form_roles = $this->createFormBuilder($defaultData)
   ->add('roles', 'entity', array(
         'class' => 'MyBundle:Role',
         'query_builder' => function(EntityRepository $er) {
              return $er->createQueryBuilder('r')
                  ->orderBy('r.description', 'ASC');
          },
          'choice_label' => 'description',
          'label' => 'My roles'
     ))          
  ->getForm();

The description field displayed in the Role object is not good enough to display it to users of the application. So I wanted to transform it. I already used transformers in a AbstractType class when I create the querybuilder with each property I want to see but never in the entity type.

So I created a RoleTransformer class like this :

class RoleTransformer implements DataTransformerInterface {
  public function transform($entity) {
   $substitution_value = null;

   switch ($entity->getDescription()) {
       case 'ROLE_INPUT':
           $substitution_value = "the value I want to see for this role";
           break;
       case 'ROLE_VALIDATION':
           $substitution_value = "the value I want to see for this role";
           break;
       case 'ROLE_ADMIN':
           $substitution_value = "the value I want to see for this role";
           break;
       default:
           $substitution_value = "the value I want to see for this role";
    }

    return $substitution_value;
  }

  public function reverseTransform($substitution_value) {
     return substitution_value; //the form is not submitted, I have no interest in reverse transformation I think.
  }
}

In the controller where I build the form I add this :

$role_transformer = new RoleTransfomer() // not sure if I have to pass something or if it is done by the framework

and I add on the form builder (before the ->getForm()):

->addModelTransformer($role_transformer)

I thought I would have a Role Object passed to the transform method but it is an array and unfortunatly it is empty.

I think I am too far from the solution, can somebody help me ?

Thank you.

1

1 Answers

0
votes

Why not take that logic and inject it directly into the choice_label with an anonymous function like explained in here:

http://symfony.com/doc/current/reference/forms/types/choice.html#choice-label

'choice_label' => function ($value, $key, $index) {
    switch ($value) {  // This may actually be key depending on how you have it setup
       case 'ROLE_INPUT':
           $substitution_value = "the value I want to see for this role";
           break;
       case 'ROLE_VALIDATION':
           $substitution_value = "the value I want to see for this role";
           break;
       case 'ROLE_ADMIN':
           $substitution_value = "the value I want to see for this role";
           break;
       default:
           $substitution_value = "the value I want to see for this role";
    }
    return $substitution_value;
},