【问题标题】:How to pre-select a form radio item with Symfony 2?如何使用 Symfony 2 预先选择表单单选项目?
【发布时间】:2013-02-14 14:47:30
【问题描述】:

我正在制作语言选择表:

    $currentLocale = "en_US"; // This is indeed sent to the formType

    $langs = array(
        'fr_FR' => 'fr',
        'en_US' => 'en'
        );

    $builder->add('language', 'language', array(
        'choices' => $langs,
        'expanded' => true,
        'multiple' => false,
        'required' => false,
        'label' => false,
    ));

HTML 代码如下所示(简化):

<div id="languageForm_language">
    <input type="radio" value="fr_FR">
    <input type="radio" value="en_US">
</div>

如何根据$currentLocale 值预选第二项?

【问题讨论】:

  • 此表单是否也绑定到数据对象,还是“普通”表单?

标签: forms symfony checkbox radio-button


【解决方案1】:

在您的 $langs 数组中,您可以像这样指定键值对:

array(
  0 => 'value1',
  1 => 'value2'
)

现在,例如要预选value2,可以将data属性设置为value2中的键:

$builder->add('language', 'choice', array(
    'choices' => $langs,
    'expanded' => true,
    'multiple' => false,
    'required' => false,
    'label' => false,

    'data' => 1
));

据此,您可以将data 属性设置为您的$currentLocale 变量以预先选择它。 您的代码应如下所示:

$currentLocale = "en_US"; // This is indeed sent to the formType

$langs = array(
    'fr_FR' => 'fr',
    'en_US' => 'en'
);

$builder->add('language', 'choice', array(
    'choices' => $langs,
    'expanded' => true,
    'multiple' => false,
    'required' => false,
    'label' => false,
    'data' => $currentLocale
));

注意:add() 方法的第二个参数应该是choice 而不是language

【讨论】:

  • 我刚试了一下,第二个参数有错误,'languante'应该是'choice',因为它是一个选择字段。这段代码对我有用
  • 我知道我的代码应该可以工作。但是,它仍然不适合我......我想我在某个地方错过了一些东西......
  • 您将第二个参数更改为choice? 编辑了我的答案,添加了适合我的代码
  • 这正是我要找的。谢谢:)
  • 好吧,如果选择中有 3 个选项,即 0,1 和 2,并且我用 'data' => 1 预选,那么我不能再选择 2 但我可以选择 0。它会忽略所有更大的选项比默认值。为什么?!
【解决方案2】:

如果表单与模型对象一起使用,只需在对象本身上设置语言,然后再将其传递给表单:

$object->setLanguage($currentLocale);
$form = $this->createForm('some_form_type', $object);

否则,将data option 设置为默认语言键:

$builder->add('language', 'language', array(
    'choices' => $langs,
    'data'    => $currentLocale,
    // ...
));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 2015-05-12
    相关资源
    最近更新 更多