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

David Morales picture David Morales · May 9, 2013 · Viewed 8.1k times · Source

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)

Answer

Maksim Kotlyar picture Maksim Kotlyar · Jul 24, 2013

I think you looking for this http://symfony.com/doc/master/cookbook/form/use_empty_data.html#option-2-provide-a-closure

Let's say you have data Money object which takes two arguments amount and currency. Here's a form type for such object:

<?php
class MoneyType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('amount', 'number')
            ->add('currency', 'text')
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Foo\Model\Money',
            'empty_data' => function (FormInterface $form) {
                return new Money(
                    $form->getData()['amount'],
                    $form->getData()['currency']
                );
            },
        ));
    }
}