createproblem
createproblem

Reputation: 1612

How to pass custom options to a Symfony form

I've to pass a custom option to a symfony form. I followed the documentation setp by step but my options will not pass.

The FormType

class AdvertType extends AbstractType
{
    /**
     * {@inheritDoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $entityManager = $options['em'];
    }

    /**
     * {@inheritDoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {    
        $resolver->setRequired(array(
            'em',
        ));

        $resolver->setAllowedTypes(array(
            'em' => 'Doctrine\Common\Persistence\ObjectManager',
        ));
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'advert';
    }
}

Here is the Code from the controller.

$form = $this->createForm(new AdvertType(), new Advert(), array(
    'em' => $this->getDoctrine()->getManager(),
));

Symfony will throw an exception that my option em is missing.

Exception: The required option "em" is missing.

I followed the tutorial to add a data transformers: http://symfony.com/doc/current/cookbook/form/data_transformers.html

I cleared my cache and restarted my web server but nothing will work. What did I wrong? Did I missed a configuration to pass my $options? It looks like the $options array from the controller I passed will never reach the buildForm method.

I'm using Symfony v2.3.5. For testing I updated to the latest (2.3.6) but the problem still exists.

Cheers.

Upvotes: 2

Views: 4531

Answers (2)

createproblem
createproblem

Reputation: 1612

I used my form twice (in different ways) so the error results from the wrong usage. I looked on the wrong place for the error. The code in general is correct. Sorry for that.

Upvotes: 1

antony
antony

Reputation: 2893

I've copied your code and used it successfully (Symfony 2.3.6). It worked! You shouldn't have to clear your cache. So I'm not sure what's wrong. You should also consider adding the data_class option in your resolver if you want to constrain the form to your Advert object, e.g.

    $resolver
        ->setDefaults(array(
            'data_class' => 'Your\Bundle\Entity\Advert',
        ))
    ;

Upvotes: 3

Related Questions