Skip to content
MachineName.php 2.36 KiB
Newer Older
Earl Miles's avatar
Earl Miles committed
<?php

/**
 * @file
 * Contains \Drupal\views\Plugin\views\field\MachineName.
namespace Drupal\views\Plugin\views\field;
Earl Miles's avatar
Earl Miles committed
/**
 * Field handler which allows to show machine name content as human name.
Earl Miles's avatar
Earl Miles committed
 * @ingroup views_field_handlers
 *
 * Definition items:
 * - options callback: The function to call in order to generate the value options. If omitted, the options 'Yes' and 'No' will be used.
 * - options arguments: An array of arguments to pass to the options callback.
class MachineName extends FieldPluginBase {
Earl Miles's avatar
Earl Miles committed
  /**
   * @var array Stores the available options.
   */
  public function getValueOptions() {
    if (isset($this->valueOptions)) {
Earl Miles's avatar
Earl Miles committed
      return;
    }

    if (isset($this->definition['options callback']) && is_callable($this->definition['options callback'])) {
      if (isset($this->definition['options arguments']) && is_array($this->definition['options arguments'])) {
        $this->valueOptions = call_user_func_array($this->definition['options callback'], $this->definition['options arguments']);
Earl Miles's avatar
Earl Miles committed
      }
      else {
        $this->valueOptions = call_user_func($this->definition['options callback']);
Earl Miles's avatar
Earl Miles committed
      }
    }
    else {
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['machine_name'] = array('default' => FALSE);
Earl Miles's avatar
Earl Miles committed

    return $options;
  }

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
Earl Miles's avatar
Earl Miles committed

    $form['machine_name'] = array(
      '#title' => $this->t('Output machine name'),
      '#description' => $this->t('Display field as machine name.'),
Earl Miles's avatar
Earl Miles committed
      '#type' => 'checkbox',
      '#default_value' => !empty($this->options['machine_name']),
    );
  }

  public function preRender(&$values) {
  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
Earl Miles's avatar
Earl Miles committed
    $value = $values->{$this->field_alias};
    if (!empty($this->options['machine_name']) || !isset($this->valueOptions[$value])) {
      $result = $this->sanitizeValue($value);
Earl Miles's avatar
Earl Miles committed
    }
    else {
      $result = $this->valueOptions[$value];
Earl Miles's avatar
Earl Miles committed
    }

    return $result;
  }