【问题标题】:Symfony 2 add choices from arraySymfony 2 从数组中添加选择
【发布时间】:2012-06-10 10:11:35
【问题描述】:

我在 symfony 中的表单有问题。

首先是代码:

$test = array();
    foreach($docGrp as $dc){
        $test[] = $dc->getGruppenName();
    }
    $form = $this->createFormbuilder($document)
        ->add('gruppe', 'choice', array(
        'choices'   =>array(
            'Gruppen'   =>  $test,
        ),
        'multiple'  =>  true,
        'expanded'  => true,
    ))
        ->getForm();

我希望数组显示为复选框,并且它的值应该是数组中的值。但是,我得到一个例外,上面写着

"在渲染模板时抛出异常("警告:strtr() 期望参数1为字符串,给定数组"

因此,如果我将选项更改为“Gruppen =>”测试“它可以工作。但它违背了目的,我需要从数组中取出这些值。

如果有人知道我的意思,帮助会很酷:)

到目前为止 阿迪

【问题讨论】:

    标签: forms symfony


    【解决方案1】:

    问题在于您在表单中传递选项的方式。因为 $test 是一个数组,你实际上是通过一个 2d 数组作为选择选项,例如array('Gruppen' => array(....)),这是不允许的。

    我已经看到在 Symfony 中使用多选小部件时二维数组可以工作。随着尺寸的增长,小部件会缩进选项。但它不适用于复选框。 你想要做的是传递一个数组,如:

    $countries = array(
        'au' => 'Australia',
        'at' => 'Austria',
        'az' => 'Azerbaijan',
        ...
    );
    

    数组键是值。

    $form = $this->createFormbuilder($document)
        ->add('country_code', 'choice', array(
            'choices'   => $countries
            'multiple'  =>  true,
            'expanded'  => true,
        )
    );
    

    【讨论】:

    • 天哪,我现在感觉好傻。。感谢先生的帮助,我搜索了 2 个小时的解决方案,就这么简单!真是太感谢你了!
    【解决方案2】:

    试试这个代码:

    foreach($docGrp as $dc)
    {
        $test[] = array($dc->getGruppenID()=>$dc->getGruppenName());
    }
    
    $form = $this->createFormbuilder($document)
        ->add('gruppe', 'choice', 
          array('choices' =>$test
        ),
        'multiple'  =>  true,
        'expanded'  => true,
    
    ))
        ->getForm();
    

    【讨论】:

      猜你喜欢
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 2022-09-29
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多