Reputation: 974
First of all, with reference to possible duplication, I have to say that it is not the same thing because he's trying to access it and I'm trying to assign the value. And I saw that before and it didn't help me.
I'm trying to set the entity field data before I show the form, and I've tried several modes and none have worked for me and I really don't understand it. I'm working on Symfony 4
This is the field of the form with the option "mapped" => false
->add('roleGroup', EntityType::class, array(
'label' => "Grupo que recibira los correos de validación como Administración",
'required' => false,
"mapped" => false,
'placeholder' => 'Elige el Grupo',
'class' => RoleGroup::class,
'label_attr' => array(
'class' => 'control-label'
),
'attr' => array(
'class' => 'form-control select',
)
))
Then in the controller I try to assign the value, but without success:
$form["roleGroup"]->setData(21);
I have also tried with:
$form->get("roleGroup")->setData(21);
return $this->render('configuration/index.html.twig',
[
'id' => $id,
'title' => "General",
'partial' => "general.html.twig",
'form' => $form->createView(),
]);
Can someone tell me what's happening?
Thanks!
Upvotes: 0
Views: 1771
Reputation: 3495
Since your form field is type of EntityType::class
, expected data should be an object of type RoleGroup::class
while you're trying to pass an integer value.
Therefore you need to fetch your entity and pass it as field data. Supposing that 21
is the id
of your entity, it should be something like this in your Controller
$em = $this->get('doctrine.orm.entity_manager');
$entity = $em->getRepository(RoleGroup::class)->findOneBy(['id' => 21]);
$form->get('roleGroup')->setData($entity);
Alternatively you can also set data
directly on your form field as default value
->add('roleGroup', EntityType::class, array(
...
'data' => $entity
));
Upvotes: 1