Flo*_*ild 7 forms choice custom-field-type symfony
有没有办法让Symfony <select>根据给定choices选项的真实性呈现具有禁用选项的表单类型?
我看到这个线程(感谢DonCallisto)关于禁用选择扩展选项; 但是我不希望有更多的选择.我想保留一个select残疾人的元素options.
$builder->add('list', 'choice', array(
'choices' => array(
array(
'value' => 1,
'label' => '1',
'disabled' => false
),
array(
'value' => 2,
'label' => '2',
'disabled' => false
),
array(
'value' => 3,
'label' => '3',
'disabled' => true
)
),
// Instead of
// 'choices' => array(
// 1 => 'Option 1',
// 2 => 'Option 2',
// 3 => 'Option 3'
// )
);
# Which would render to the following element
<select [...]>
<option value='1'>1</value>
<option value='2'>2</value>
<option value='3' disabled='disabled'>3</value>
</select>
Run Code Online (Sandbox Code Playgroud)
我只是找不到方法......是否有必要建立自己的字段类型?
Jac*_*mri 23
从版本2.7开始,Symfony引入了一种使用callable设置选择属性的方法,这正是您所需要的.
此代码取自Symfony官方文档
$builder->add('attending', ChoiceType::class, array(
'choices' => array(
'Yes' => true,
'No' => false,
'Maybe' => null,
),
'choices_as_values' => true,
'choice_attr' => function($val, $key, $index) {
// adds a class like attending_yes, attending_no, etc
return ['class' => 'attending_'.strtolower($key)];
},
));
Run Code Online (Sandbox Code Playgroud)
您可以使用'choice_attr'和传递一个函数,该函数将决定是否添加 disabled属性,具体取决于所选的值,键或索引.
...
'choice_attr' => function($key, $val, $index) {
$disabled = false;
// set disabled to true based on the value, key or index of the choice...
return $disabled ? ['disabled' => 'disabled'] : [];
},
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12069 次 |
| 最近记录: |