Symfony 3.3 Form - EntityType field does not select option Symfony 3.3 Form - EntityType field does not select option symfony symfony

Symfony 3.3 Form - EntityType field does not select option


Another solution is using a Data Transformer.

Remove the data attribute from the productCategory type, and add a data transformer to the end of the build method:

    $builder->get('productCategory')        ->addModelTransformer(new CallbackTransformer(            function ($id) {                if (!$id) {                    return;                }                return $this->em->getRepository('AppBundle:ProductCategory')->find($id);            },            function($category) {                return $category->getId();            }        ));

If you use the same transformer in multiple places, you can extract it into its own class.


My workaround was like this ...pass data and entity manager to formType.

$form = $this->createForm(new xxxType($this->get('doctrine.orm.entity_manager')), xxxEntity, array(        'method' => 'POST',        'action' => $this->generateUrl('xxxurl', array('id' => $id)),        'selectedId' => xxxId,    ));

setDefaultOptions in form Type initialize as an empty array for selectedId

$resolver->setDefaults(array(        'data_class' => 'xxx',        'selectedId' => array()    ));

and in builder

->add('productCategory', EntityType::class,            array(                'class' => ProductCategory::class,                'choice_label' => 'name',                'choice_value' => 'id',                'placeholder' => '',                'label_attr' => array('title' => 'Category for this product'),                'query_builder' => function (ProductCategoryRepository $v) {                    return $v->createQueryBuilder('v')                        ->orderBy('v.name',' ASC');                },                'data'=>$this->em->getReference("xxx",$options['selectedId'])            ))

for more details, you can see this answer Symfony2 Setting a default choice field selection