Score:1

Change the state of a checkboxes field

pe flag

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?

sanzante avatar
ph flag
Does this answer your question? [Using #states in a form with checkboxes](https://drupal.stackexchange.com/questions/290079/using-states-in-a-form-with-checkboxes)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.