1

I know how to use conditions with Form API for fields like text-field, checkbox, for example, showing or hiding a field when a checkbox is checked.

$form['lorem'] = [
  '#type' => 'checkbox',
  '#attributes' => [
    'name' => 'field_lorem',
  ]
];

$form['ipsum'] = [
  '#type' => 'checkbox',
  '#states' => [
    'visible' => [
      ':input[name="field_lorem"]' => ['checked' => true]
    ],
  ],
];

However, I can't manage to do it with a checkboxes field.

// This code does not work.
$form['lorem'] = [
  '#type' => 'checkbox',
  '#attributes' => [
    'name' => 'field_lorem',
  ]
];

$options = [
  'test_1' => 'Test 1',
  'test_2' => 'Test 2',
];

$form['ipsum'] = [
  '#type' => 'checkboxes',
  '#options' => $options,
  '#states' => [
    'visible' => [
      ':input[name="field_lorem"]' => array('checked' => true)
    ],
    // Ideally, I would like to have all the checkboxes checked but the problem is mainly at the state level
    'checked' => [
      ':input[name="field_lorem"]' => ['checked' => TRUE],
    ],
  ],
];

I can do it with custom JavaScript code, but I ideally wanted to do it with the form API.

What #states property do I need to achieve this?

1

2 Answers 2

1

You need to add #states to every checkbox.

$form['select_all'] = [
  '#title' => $this->t('Select all'),
  '#type' => 'checkbox',
  '#attributes' => [
    'name' => 'all'
  ]
];

$options = [
 'item_0' => 'value',
 'item_1' => 'value',
 'item_2' => 'value',
];

$form['my_checkboxes'] = [
 '#type' => 'checkboxes',
 '#options' => $options,
 'item_0' => [
    '#states' => [
      'checked' => [
        ':input[name="all"]' => [
          'checked' => TRUE
        ]
      ]
    ]
  ]
];

foreach ($options as $key => $item) {
  $form['my_checkboxes'][$key]['#states']['checked'][':input[name="all"]']['checked'] = TRUE;
}
1

You can wrap the checkboxes in a details (fieldset).

$form['controlling_checkbox'] = [
  '#type' => 'checkbox',
  '#title' => ['Switch me on and off'],
];
$options = ['a' => 'b', 'c' => 'd'];
$form['wrapper'] = [
  '#type' => 'details',
  '#title' => 'Wrap me up',
  '#collapsible' => TRUE,
  '#open' => TRUE,
  '#states' => [
    'disabled' => [
      ':input[name="controlling_checkbox"]' => [
          ['checked' => TRUE],
      ],
    ],
  ]
];
$form['wrapper']['lots_of_boxes'] = [
  '#type' => 'checkboxes',
  '#options' => $options,
];

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.