Unable to retrieve checkbox values from a template file I have created a checkbox option for a field.


Category


One
Two
Three
Four



This is the code I am using.

    {% for key, item in content.field_room_category if key|first != '#' %}
         &lt;li&gt;{{ item }}&lt;/li&gt;
    {% endfor %}


In the &lt;li&gt; tag, I get all the checked values, but I also need to check which values have been selected.

For this, I tried {{ item.value }}, {{ item.content }}, and {{ item['#title'] }}. None of them worked.

Is there any way to get all the checkbox items with their values?


  


I want to achieve something similar to the image above. If the item is checked, I show an icon; if the item is unchecked, another icon will be shown.
Checkbox values are preprocessed so only checked ones you can get in your twig:
I think you need to preprocess your field by implementing hook_preprocess_HOOK to add unchecked ones to your variables something like:

/**
 * Implements hook_preprocess_HOOK().
 */
function MY_MODULE_preprocess_field(&amp;$variables) {
  $element = $variables['element'];
  if ($element['#field_name'] == "field_room_category") {
    // Node object.
    $node = $element['#object'];
    // All allowed values in the field.
    $allowed_values = $node-&gt;field_room_category-&gt;getFieldDefinition()
      -&gt;getSetting('allowed_values');

    // Checked values.
    $checked_values = array_filter($element, function ($key) {
      return is_int($key);
    }, ARRAY_FILTER_USE_KEY);

    for ($i = 0; $i &lt; count($allowed_values); $i++) {
      // If the checkbox already checked add is_selected as true.
      if (isset($checked_values[$i])) {
        $variables['element'][$i]['is_selected'] = TRUE;
      }
      else {
        // If the checkbox not checked add the item with is_selected as false.
        $variables['element'][$i] = [
          '#markup'       =&gt; current(array_slice($allowed_values, $i-1, 1, FALSE)),
          '#allowed_tags' =&gt; [],
          'is_selected'   =&gt; FALSE,
        ];
      }
    }
  }
}


now in your twig you can do something like:

  {% for key, item in element if key|first != '#' %}
     &lt;li&gt;
       {% if item.is_selected %}
         &lt;span style="color: green;"&gt;  {{ item }} &lt;/span&gt;
       {% else %}
         &lt;span style="color: red;"&gt;  {{ item }} &lt;/span&gt;
       {% endif %}
     &lt;/li&gt;
   {% endfor %}