forms - Symfony 如何禁用默认选项

标签 forms symfony twig

根据这个网址 Set Default Text in a Select (drop-down) box/menu我需要添加 disabled symfony 中占位符的属性。这是我的代码。

$builder
    ->add('name', 'text', array(
        'label' => 'Business Name',
    ))           
    ->add('country', 'entity', array(
        'class' => 'AppBundle:Country',
        'property' => 'name',
        'placeholder' => 'Please select',
    )); 

现在我需要添加 disabled喜欢 <option value="" disabled>Please select</option>
我该怎么做?最好的方法是什么?

最佳答案

如果这个话题仍然开放......我今天遇到了类似的问题并以这种方式管理它。 (在 symfony 2.7.10 中测试)

显然 placeholder是 vars 中的独立属性,因此您不能在 finishView 中选择它.

在您的 buildForm方法:

$builder->add('label', 'choice', array(
    'data' => $var, // your default data
    'read_only' => true,
    'placeholder' => false, // implement a condition to check wether you want the choice read only
));

实现 finishView方法(接口(interface)实现来自AbstractType):
public function finishView(FormView $view, FormInterface $form, array $options)
{
    foreach ($view->children['country']->vars['choices'] as $id => $choiceView) {
        // implement a condition to prevent the accepted/wanted option be disabled
        if ($id != $yourAcceptedValueId) {
            $choiceView->attr = ['disabled' => 'disabled'];
        }
    }
}

不幸的是,选择列表中没有占位符选项,因此您必须实现两个设置来实现这一点。

问候

关于forms - Symfony 如何禁用默认选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28854164/

相关文章:

Symfony 2.0 KnpMenu 自定义模板

drupal - 获取twig文件中的base_path -- Drupal 8

javascript - 动态添加表单和输入复选框到 HTML 问题

forms - 如何在 Zend Framework 2 中实现表单预览页面?

php - 使用for循环将记录添加到数据库

twig:检查对象中所有包含的数组是否为空

twitter-bootstrap - Toopay/bootstrap-markdown 的预览按钮不起作用

javascript - 使用 JavaScript 删除超过 1 个选择选项

Symfony 4,一种从现有数据库生成实体的方法?

php - Symfony 3.1.4clearCache脚本需要generator-bundle开发包