Skip to content

Create a "virtual" field for a view

Willi edited this page Apr 16, 2018 · 2 revisions

my_module/src/Plugin/views/field/MyField.php

class MyField extends FieldPluginBase {

  public function query() {
  // Leave empty to avoid a query on this field.
  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['node_type'] = array('default' => '<node_typ>');

    return $options;
  }

  /**
   * Provide the options form.
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    $types = NodeType::loadMultiple();
    $options = [];
    foreach ($types as $key => $type) {
      $options[$key] = $type->label();
    }
    $form['node_type'] = array(
      '#title' => $this->t('Which node type should be flagged?'),
      '#type' => 'select',
      '#default_value' => $this->options['node_type'],
      '#options' => $options,
    );

    parent::buildOptionsForm($form, $form_state);
  }

  /**
   * @{inheritdoc}
   */
  public function render(ResultRow $values) {
    ...
    return MyField;
  }

}

my_module.views.inc

function my_module_views_data_alter(&$data) {
  $data['rng_custom']['table']['group'] = t('RNG Custom');
  $data['rng_custom']['table']['join'] = array(
    // #global is a special flag which let's a table appear all the time.
    '#global' => array(),
  );

  $data['my_module']['<foo_bar>'] = [
    'title' => t('foo bar'),
    'field' => [
      'title' => t('bar foo'),
      'help' => t('foo foo foo foo'),
      'id' => '<id>',
    ],
  ];
}