I have an entity with a OneToOne association to another entity. For these purposes I’ll call the initial entity “Parent” and the associated Entity “Child”.
I have a Parent form working fine that embeds the child form and all the form elements for both entities appear, and I can save the data fine in the controller.
Now I want to set defaults for a number of attributes in the embedded doctrine entity. I could set values for the new entity in the controller, but the child entity is created in the embedded form class:
// Parent form
class Parent extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
//parent->add(...)
$builder->add('child', new Child(), array());
}
// In Child Form
class Child extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('visibilitycode', 'entity', array('label' => 'Visibility', 'class'=>'Acme\MyBundle\Entity\Visibility', 'property'=>'name'));
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Acme\MyBundle\Entity\Child',
);
}
Many of these defaults are for associated foreign keys, so if I was setting them in the controller I might use something like this:
$child->setVisibilityCode($em->getReference('AcmeMybundle:Visibility', 'P'));
Two solutions are offered to you (or maybe more 🙂 ):
Childentity itself ( in constructor for example)use the
empty_dataoption of the Form component: