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