选择字段默认值 [英] Choice field default value

查看:106
本文介绍了选择字段默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的格式如下:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('type', ChoiceType::class, array(
        'expanded' => true,
        'multiple' => false,

        'choices' => array(
            'Friend' => 'friend',
            'Guide' => 'guide'
        )
    ));
}

在呈现表单时,如何使朋友" 复选框在默认情况下处于选中状态?

How can I make 'Friend' checkbox to be checked by default when the form is rendered ?

推荐答案

我认为您应该尝试使用data选项,但这只是在您甚至没有将数据保存在对象内部的情况下,因为将会覆盖其他内容.

I think you should try with data option, but it's just in the case where you don't even have a data saved inside your object, because it will override it else.

重要:这对创建操作很有用,但对编辑操作不利.

Important : It's good for create action, but not for edit action.

 public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('type', ChoiceType::class, array(
            'expanded' => true,
            'multiple' => false,

            'choices' => array(
                'Friend' => 'friend',
                'Guide' => 'guide'
            ),
            'data' => 'friend'
        ));
    }

官方链接

Official link

提取:

创建表单时,每个字段最初都会显示 表单域对象的相应属性(如果对象是 绑定到表格).如果您要覆盖的初始值 表格或单个字段,您可以在数据选项中进行设置

When you create a form, each field initially displays the value of the corresponding property of the form's domain object (if an object is bound to the form). If you want to override the initial value for the form or just an individual field, you can set it in the data option

更新是否需要空值:

作为下面的答案,如果需要在任何情况下更新默认值,请将data替换为empty_data

As the answer below, replace data with empty_data if you need in any case to update default value

这篇关于选择字段默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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