简体   繁体   中英

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.

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, eg

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM