【问题标题】:Warning: Missing argument 1 for BannerType::__construct()警告:BannerType::__construct() 缺少参数 1
【发布时间】:2017-05-05 11:49:00
【问题描述】:

如何使用 symfony3 中的 createForm 方法将参数传递给控制器​​中的自定义表单类型? 参数是“类型” 在 BannerType.php 中:

public function __construct($type){
    $this->type = $type;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Banner\BannerBundle\Entity\Banner',
        'type' => null,
    ));
}

在 BannerController.php 中:

$form = $this->createForm(BannerType::class, $entity, array(
    'typee' => $type,
));

【问题讨论】:

  • 您在 createForm 参数中有错字:'typee' 而不是 'type'。
  • 谢谢,但这是一个错字没有影响

标签: php symfony


【解决方案1】:

创建对象时,您没有传递任何参数。这就是您收到此消息的原因。您可以从 buildForm 方法中可用的 options 变量中获取类型参数。

这是您的表单类的示例:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $myType = $options['type'];
    if ($myType == NULL){
        // TODO: 
    }
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Banner\BannerBundle\Entity\Banner',
        'type' => null,
    ));
}

【讨论】:

    【解决方案2】:

    您的问题的答案已经在 StackOverflow 上。您可以阅读它 here 。我认为您需要删除 __construct 函数,因为从 Symfony 2.8 您必须将字符串 FormType::class 传递给 createForm 方法,而不是对象的实例,并且此字符串可能稍后处理作为没有任何参数的构造函数。然后它应该工作:)

    【讨论】:

      【解决方案3】:

      当您想将一些参数传递给FormType 的构造函数并能够通过createForm 实例化它时,您需要使用适当的form.type 标记将其注册为服务,如下所示:

      # src/AppBundle/Resources/config/services.yml
      services:
          app.form.type.banner:
              class: AppBundle\Form\Type\BannerType
              arguments:
                  - '%type%'
              tags:
                  - { name: form.type }
      

      但这只允许您传递服务容器中可用的参数,即其他服务、参数等。

      你想做的实际上没有意义。您不能期望在FormType 类的构造函数中获得参数,而是通过createForm() 的第三个参数传递它,该参数旨在获取选项,而不是构造函数的参数。看起来您尝试以错误的方式执行此操作,但我需要更多代码并知道您要做什么才能告诉您应该如何完成。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-14
        • 1970-01-01
        • 2017-02-22
        • 1970-01-01
        相关资源
        最近更新 更多