1

I am trying to render a choice field with checkboxes and I want, in edit mode, this to have the data the user previously checked meaning a way to set default data. the below code does not work. can someone help please. thank you

$days = array("monday" => "monday","tuesday" => "tuesday");
$builder->add('channels', 'choice', array(
            'choices' => array(
                'days'  => $days,                
            ),
            'multiple' => true,
            'expanded' => true,
            'required' => true,
            'data' => array("choices" => array("days" => array("monday")))
        ));

3 Answers 3

4

I think this should work:

$builder->add(
    'channels',
    'choice',
    array(
        ...
        'data' => array("monday"),
    )
)
Sign up to request clarification or add additional context in comments.

3 Comments

try 'data' => array('monday'=>'Monday','tuesday'=>'Tuesday')
it is giving me the same result
I have realized that it's working I just forgot something in my variables when I tested with an array with multiple elements . CiTNOH is also explaining it
3

This One worked for me (Symfony 2.3.x):

$days = array("monday" => "Monday","tuesday" => "Tuesday","wednesday" => "wednesday","thursday" => "thursday");
    $builder->add('channels', 'choice', array(
        'choices' => array(
            'days'  => $days,                
        ),
        'multiple' => true,
        'expanded' => true,
        'required' => true,
        'data' => array("wednesday","thursday","tuesday")
    ));  

Note: Use the key index to set the Data not the value. "Tuesday" will not work here as "tuesday" does.

1 Comment

Still works in Symfony v3.3 (when used with regular v3.3 syntax). Tnx.
-1

Remove the choices key in the data array:

$builder->add( 'channels', 'choice', array( ... 'data' => array("monday") ) );

1 Comment

Your solution is throwing the following exception : "Notice: Array to string conversion in /xxx/xxx/xxx/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php line 457"

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.