Skip to main content

Drupal 8: Passing theme suggestions to checkbox(es) and settings default values

This is how to make your custom theme to include extra suggestions based on the term vocabulary name and how to set a default value for the checkbox if you are on the taxonomy/term-id page.

function my_theme_suggestions_input_alter(&$suggestions, array $variables) {

  if ($variables['element']['#type'] === 'checkbox') {
    if (isset($variables['element']['#parents'][0])) {
        $suggestions[] = $variables['theme_hook_original'].'__'.$variables['element']['#parents'][0];
    }
  }
}

Now this will provide a suggestion based on the custom entity reference name field.

e.g.    input--checkbox--field-vocabulary-taxonomy--ref-target-id.html.twig

Next we need to see if the current taxonomy term page matches the current input checkbox exposed views filter.

function my_theme_preprocess_input__checkbox(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
    if ($variables['attributes']['value'] == $term_id) {
      $variables['attributes']['checked'] = 'checked';
    }
  }
}

And that's it. When you visit /taxonomy/term-id page your exposed filter checkbox will get the default value from the term-id url arg.

views template

Latest Articles

VSCode Drupal Coding Standards Setup (From Scratch) admin_pixelthi… Mon, 12/22/2025 - 16:01 VSCode Drupal Coding Standards Setup (From Scratch)

VSCode Drupal Coding Standards Setup (From Scratch)

vscode
Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter