Search code examples
symfonysymfony-2.2

How do I set Entity constructor parameter from a Form Type?


I need to pass a parameter to the constructor of an Entity that is being used in a Form Type.

I'm setting the entity from the Form Type in the setDefaultOptions method:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'MyApp\MyBundle\Entity\MyEntity'
    ));
}

I would like to use something like this:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'MyApp\MyBundle\Entity\MyEntity',
        'my_parameter' => 'some value'
    ));
}

so that it would be injected through the constructor.

Is this possible? (I'm using Symfony 2.2)


Solution

  • The form type never creates any entity object. So it seems it doesn't make any sense to pass arguments for entity constructor.

    Setting data_class option is not even necessary to couple the form with entity object. In most cases data class is guessed based on an object passed to form builder.

    From Symfony docs:

    Every form needs to know the name of the class that holds the underlying data (e.g. Acme\TaskBundle\Entity\Task). Usually, this is just guessed based off of the object passed to the second argument to createForm (i.e. $task). Later, when you begin embedding forms, this will no longer be sufficient. So, while not always necessary, it's generally a good idea to explicitly specify the data_class option (...)

    edit:

    An example:

    class SomeController extends Controller
    {
        public function fooAction()
        {
             $entityObject = new MyEntity($someArgument);
    
             // now we create form:
             $form = $this->createForm(new BarFormType(), $entityObject);
    
             // then you can bind form:
             $form->bind($this->getRequest());
    
             // ... and enjoy your data :)
             printf("Hello %s", $entityObject->getValuePassedByUserViaForm());
        }
    }