0

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 != '#' %}
         <li>{{ item }}</li>
    {% endfor %}

In the <li> 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?

enter image description here

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.

1 Answer 1

1

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(&$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->field_room_category->getFieldDefinition()
      ->getSetting('allowed_values');

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

    for ($i = 0; $i < 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'       => current(array_slice($allowed_values, $i-1, 1, FALSE)),
          '#allowed_tags' => [],
          'is_selected'   => FALSE,
        ];
      }
    }
  }
}

now in your twig you can do something like:

  {% for key, item in element if key|first != '#' %}
     <li>
       {% if item.is_selected %}
         <span style="color: green;">  {{ item }} </span>
       {% else %}
         <span style="color: red;">  {{ item }} </span>
       {% endif %}
     </li>
   {% endfor %}
1
  • I have added the above function in mythemename.theme.php. Nothing changed, I have just put a print_r on $variables['element']; and it shows empty, so its not even entering the if condition. This is the function name I have used mytheme_preprocess_node__content_type_products it is a custom content type. Any changes needed?
    – Mann
    Commented Apr 1, 2020 at 18:47

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.