如何将自定义选项传递给 Symfony 表单 [英] How to pass custom options to a Symfony form

查看:39
本文介绍了如何将自定义选项传递给 Symfony 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将自定义选项传递给 symfony 表单.我一步一步地遵循了文档设置,但我的选择不会通过.

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

表单类型

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';
    }
}

这是控制器的代码.

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

Symfony 会抛出一个异常,说明我的选项 em 丢失了.

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

异常:缺少必需的选项em".

Exception: The required option "em" is missing.

我按照教程添加了一个数据转换器:http://symfony.com/doc/current/cookbook/form/data_transformers.html

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

我清除了缓存并重新启动了我的网络服务器,但没有任何效果.我做错了什么?我是否错过了传递 $options 的配置?看起来我传递的控制器中的 $options 数组永远不会到达 buildForm 方法.

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.

我使用的是 Symfony v2.3.5.为了测试我更新到最新的(2.3.6)但问题仍然存在.

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

干杯.

推荐答案

我使用了我的表单两次(以不同的方式)所以错误是由错误的用法造成的.我在错误的地方寻找错误.代码一般是正确的.对不起.

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.

这篇关于如何将自定义选项传递给 Symfony 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆