0

I have a taxonomy terms view, filtered by a vocabulary. I would like to add the dashes before the term name like in the Parent terms field on the edit term page. The code in TermForm.php does that when creating $options using str_repeat based on the item's depth.

This is the code from TermForm.php:

$tree = $taxonomy_storage->loadTree($vocabulary->id());
$options = ['<' . $this->t('root') . '>'];
if (empty($parent)) {
  $parent = [0];
}

foreach ($tree as $item) {
  if (!in_array($item->tid, $exclude)) {
    $options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
  }
 }
}

I copied core/modules/views/templates/views-view-field.html.twig to my module's templates directory and renamed it views-view-field--my-view-name--name.html.twig I added hook_theme to the module file to start using the template.

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'views_view_field__my_view_name__name'=> [
      'render element' => 'elements',
      'template' => 'views-view-field--my-view-name--name',
    ],
  ];
}

If I add some markup to the template, like <h3>hello</h3>, hello is printed on the View's page but, no data is being passed to the template.

Ultimately I need to get the term object and update it with

str_repeat('-', $item->depth) . $item->name

before passing the field to the template. I'm guessing I get the term object in a preprocessor and add the updated name field to hook_theme?

1 Answer 1

0

It turns out I don't need the template. Using hook_preprocess_views_view_field() with the following code was all that was required:

/**
 * Implements hook_preprocess_views_view_field().
 */
function my_module_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  $field_id = $field->field;
  if (
    $view->storage->id() === 'my_view_name' &&
    $view->current_display === 'my_display' &&
    $field_id === 'name'
  ) {
    $tid = $variables['row']->_entity->id();
    $label = $variables['row']->_entity->label();

    $parents = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadAllParents($tid);
    $depth = count($parents);
    $path = \Drupal::service('path_alias.manager')
      ->getAliasByPath('/taxonomy/term/' . $tid);

    $link = '<a href="' . $path . '">' . $label . '</a>';
    $variables['output'] = Markup::create(str_repeat('-', $depth) . $link);
  }
}

solved the problem.

I think this line

    $link = '<a href="' . $path . '">' . $label . '</a>';

can be improved, but it will do for now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.