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

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

问题描述

我正在使用语言选择表单:

  $ currentLocale =en_US //这确实发送到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 =radiovalue =fr_FR>
< input type =radiovalue =en_US>
< / div>

如何根据 $预先选择第二个项目 $ langs c> array你可以像下面这样指定键值对:

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

您要预先选择 value2 ,您可以从 value2 设置 data / code>:

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

'data'=> 1
));

根据这个,你可以设置数据属性添加到您的 $ currentLocale 变量中以进行预选。 您的代码应如下所示:

  $ currentLocale =en_US //这确实发送到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 ()方法应该选择不是语言


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,
    ));

The HTML code looks like this (simplified):

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

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

解决方案

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

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

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
));

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
));

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

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

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