2

In symfony form I have some choices, checkboxes.

$form->add('keywords', ChoiceType::class, array(
            'choices' => $keywords,
            'label' => 'With following keywords',
            'expanded' => true,
            'multiple' => true,
        ));

I need all checboxes selected when form is initialised. How I can do that if possible in symfony way or I will need to do that with JavaScript?

1 Answer 1

4

Just add choice_attr

$form->add('keywords', ChoiceType::class, array(
            'choices' => $keywords,
            'label' => 'With following keywords',
            'expanded' => true,
            'multiple' => true,
            'choice_attr' => function() {
                return ['checked' => 'checked'];
            },
        ));
Sign up to request clarification or add additional context in comments.

3 Comments

Medard, Thanks a lot bro :)
if you're always going to return the same array, you don't need a function for that, just use 'choice_attr' => array('checked => 'checked'); symfony.com/doc/current/reference/forms/types/…
Older comment - specs may have changed since 2016 but to clarify; As of Symfony 3.4 - 6.0 the callback is executed on each of the defined choices options. Causing checked to be applied to all choices regardless of the initial Form data state. For instance when $builder->get('keywords')->getData() = []. While 'choice_attr' => ['checked => 'checked'] executes only on the specified index of the defined choices, for example 'choices' => ['choice_1' => 1] and 'choice_attr' => ['choice_1' => ['checked' => 'checked']].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.