Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following form:

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
465 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

Extract :

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

UPDATE If YOU NEED EMPTY VALUE:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...