如何使用 Symfony 2 预先选择表单单选项目? [英] How to pre-select a form radio item with Symfony 2?

查看:21
本文介绍了如何使用 Symfony 2 预先选择表单单选项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作语言选择表:

I'm working on a language choice form:

    $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 代码如下所示(简化):

The HTML code looks like this (simplified):

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

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

How could I get the second item pre-selected, according to the $currentLocale value ?

推荐答案

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

In your $langs array you can specify key value pairs like this:

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

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

Now, e.g. you want to preselect value2, you can set the data attribute to the key from value2:

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

    'data' => 1
));

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

According to this, you can set your data attribute to your $currentLocale variable to preselect it. Your code should look like this:

$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.

Note: the second parameter from the add() method should be choice not language.

这篇关于如何使用 Symfony 2 预先选择表单单选项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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