You are here

MachineName.php in Machine name 8

File

src/Plugin/Field/FieldFormatter/MachineName.php
View source
<?php

namespace Drupal\machine_name\Plugin\Field\FieldFormatter;

use Drupal\Component\Utility\Html;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @FieldFormatter(
 *  id = "machine_name",
 *  label = @Translation("Machine name"),
 *  field_types = {"machine_name"}
 * )
 */
class MachineName extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#markup' => $this
          ->viewValue($item),
      ];
    }
    return $elements;
  }

  /**
   * Generate the output appropriate for one field item.
   *
   * @param \Drupal\Core\Field\FieldItemInterface $item
   *   One field item.
   *
   * @return string
   *   The textual output generated.
   */
  protected function viewValue(FieldItemInterface $item) {

    // The text value has no text format assigned to it, so the user input
    // should equal the output, including newlines.
    return nl2br(Html::escape($item->value));
  }

}

Classes

Namesort descending Description
MachineName Plugin annotation @FieldFormatter( id = "machine_name", label = @Translation("Machine name"), field_types = {"machine_name"} )