【问题标题】:Pushing an option in a nested form with Symfony 2使用 Symfony 2 以嵌套形式推送选项
【发布时间】:2013-02-02 04:23:36
【问题描述】:

我正在使用选择框处理表单。这些方框代表不同国家/地区的比例。

因此,我创建了一个服务,该服务根据用户的偏好生成自定义值以提供选择框。这适用于第一级表单:

控制器代码:

$form = $this->createForm(new formType, $entity, array(

     // Getting the service    
     'myScales'     => $this->get('myBnd.scales'),

     // Getting user's scale preference
     'scalesLocale'  => $this->get('security.context')->getToken()->getUser()->getScaleLng(),

     ));

然后,我在 formType 中得到了显示自定义选择所需的一切:

public function buildForm(FormBuilder $builder, array $options) {

    $scaleSelect = array();        
    // Here is a custom code using $options['myScales'] and $options[scalesLocale']
    // This builds the relevant $scaleSelect

    // ....

$builder
        ->add('scale', 'choice', array(
            'choices'   => $scaleSelect
        ))
        ->add('subscale', 'collection', array(
            'type' => new subType,
            'prototype' => true,
            'allow_add' => true,
            'allow_delete' => true,
        ))

然后我需要定义嵌套的子类型。它还需要一个自定义的选择框。如何将变量 $scaleSelect 发送给它以生成(相同)适当的选择框?

【问题讨论】:

    标签: forms service nested symfony-2.1 nested-forms


    【解决方案1】:

    我想到的最快的选择:

          ->add('subscale', 'collection', array(
               'type' => new Subtype($scaleSelect),
               'prototype' => true,
               'allow_add' => true,
               'allow_delete' => true,
           ))
    

    然后在您的子类型类中:

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

    之后,您可以使用 $this->choices 在 buildform 中访问您传递的选项。 希望对您有所帮助。

    【讨论】:

    • 如果子类型作为字符串传递(->add('subscale', 'collection', ['type' => 'mySubType', ...]) )怎么办? IE。可以将自定义表单类型转换为服务(请参阅symfony.com/doc/current/cookbook/form/…)。在这种情况下,我们不能将任何东西传递给构造函数......任何解决方法?
    猜你喜欢
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2018-04-16
    • 2013-01-13
    • 1970-01-01
    • 2017-07-21
    相关资源
    最近更新 更多