In this example I show how to create a formatter plugin to provide an active trail class to highlight the link of the current page in a Views list.  This behaviour is native to Drupal menus and I could have created a menu but that would not be dynamic and anyway, I wanted to see what is involved in applying active trail classes to a Views list.

Creating a field formatter is very simple in Drupal 8 but the syntax has to be correct for it to work.  Here is the formatter.  It should belong to a custom module which is here called Mymodule and should be in the directory mymodule/src/Plugin/Field/FieldFormatter in a file called MymoduleActiveLinkFormatter.php.  This formatter provides a setting for linking to the content which is the link we want to manipulate by adding an active-trail class.  In the main part of the formatter we grab the value for the current url and then compare it with each of the items.  If the path coincides with an item then it gets the class attribute.

 

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Field\FieldFormatter\MymoduleActiveLink.
 */

 

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
 * Plugin implementation of the 'mymodule_active_link' formatter.
 *
 * @FieldFormatter(
 *   id = "mymodule_active_link",
 *   label = @Translation("Active Link"),
 *   description = @Translation("Link with active class if current url"),
 *   field_types = {
 *     "string"
 *   }
 * )
 */
class MymoduleActiveLinkFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    $options = parent::defaultSettings();

    $options['display_as_link'] = TRUE;
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form, $form_state);

    $form['display_as_link'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Link to Content'),
      '#default_value' => $this->getSetting('display_as_link'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {

    $elements = [];
    $current_path = \Drupal::service('path.current')->getPath();

    foreach ($items as $delta => $item) {
      $entity = $item->getEntity();
      $path = '/node/' . $entity->nid->value;
      if ($this->getSetting('display_as_link') && $path) {
        $elements[$delta] = [
          '#type' => 'link',
          '#title' => $item->value,
          '#url' => Url::fromUri('internal:' . $path)
        ];
        if ($path == $current_path) {
          $elements[$delta]['#attributes'] = [
            'class' => [
              'active-trail'
            ]
          ];
        }
      }
      else {
        $elements[$delta] = ['#markup' => $item->value];
      }
    }

    return $elements;
  }

}

The annotation at the top provides the crucial information to Drupal informing of the existence of the plugin.  This provides the name and field types to which it applies.

* @FieldFormatter(
 *   id = "mymodule_active_link",
 *   label = @Translation("Active Link"),
 *   description = @Translation("Link with active class if current url"),
 *   field_types = {
 *     "string"
 *   }
 * )

 

Once created, the formatter will be available anywhere there is a string field.  However, Drupal 8 is highly cached and this is a dynamic formatter, which changes from page to page dependent on the url.  For it to work in a View, cacheing for the view must be disabled.  At the time of writing it is not good enough simply to disable the render cache. 

 

Platform

Blog comments

Submitted by daviddwalter12 on Tue, 04/18/2017 - 09:49

Permalink

The connection module gives a standard custom substance field for connections. With this module, connections can be effortlessly added to any substance sorts and profiles and incorporate progressed approving and distinctive methods for putting away interior or outside connections and URLs. It likewise bolsters extra connection content title, site wide tokens for titles and title properties, target qualities, css class attribution, static rehashing values, input change, and some more.
ref:
best essay writing service

User login