我知道用树枝的解决方案,但这并不酷。也许有人知道表单类型的解决方案。
我想根据默认值设置要选择的类(CSS),例如:
<select> <option value="r" selected="selected">read</option> <option value="rw">read-write</option> <option value="n">no-access</option> </select>
我想设置类来选择:
<select class="select-r"> <option value="r" selected="selected">read</option> <option value="rw">read-write</option> <option value="n">no-access</option> </select>
表格类型:
class UserDefaultAccessSettingType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$choice = array(User::ACCESS_READ => 'read', User::ACCESS_WRITE => 'read-write', User::ACCESS_DENIED => 'no-access');
$builder
->add('month_report', 'choice', array(
'choices' => $choice,
'required' => true
))
->add('quarterly_report', 'choice', array(
'choices' => $choice,
'required' => true
))
->add('semi_annual_report', 'choice', array(
'choices' => $choice,
'required' => true
))
->add('annual_report', 'choice', array(
'choices' => $choice,
'required' => true
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => '\backend\backendBundle\Entity\UserDefaultAccessSetting',
));
}
public function getName()
{
return 'UserDefaultAccessId';
}
}
只需使用字段attr选项。根据您的代码,您将选择分配给$choice
数组,因此默认选择将是数组中的第一个值。
您可以执行以下操作:
->add('month_report', 'choice', array(
'choices' => $choice,
'required' => true
'attr' => array('class' => 'select-' . array_keys($shoice)[0])
))
如果您还想根据用户的选择动态地更改类,则需要为此编写一些JS。
就是说,我不知道您为什么在Twig中说“不酷”,因为它是样式,它可能应该在应用程序的视图组件中……实际上,如果您无论如何编写JS来处理此问题,为什么要在表单构建器中复制表示逻辑?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句