Symfony ChoiceType Default to Checkbox Checked

I’m rendering a bunch of checkboxes using a Symfony form type of ChoiceType and I want some of them to be checked by default.

It’s basically a list of transactions and the ones that fail will be checked so that the user can fix whatever caused the problem and run them failed ones again. It would be tedious to make them check what could be 100s of checkboxes to rerun the failures.

$results = $this->getJobResults($job);
$transactions_array = $data = array();
foreach ($results as $result) {
  if ($result->success != 'Success') {
    $data[] = $result->id;
  $transactions_array[$result->id] = $result->id;
$retryForm->add('transactions', ChoiceType::class, array('multiple'=>TRUE, 'expanded'=>TRUE, 'choices'=>$transactions_array, 'data'=>$data));

What I needed to do was build the $data array to contain the same values in $transactions_array (choices) of the checkboxes I want checked. When the form is rendered, if the checkbox value is in the $data array, it’s checked by default. For some reason that wasn’t obvious in the Symfony documentation.

Share Button