2

I just created a new custom field in a view, but I would like to use replacement patterns in that field. Is it possible to do this?

class CustomButtonField extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function usesGroupBy() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    // Do nothing -- to override the parent query.
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['target'] = ['default' => FALSE];
    $options['class'] = ['default' => FALSE];
    $options['text'] = ['default' => FALSE];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    $form['target'] = array(
      '#title' => $this->t('The target id of the button'),
      '#type' => 'textfield',
      '#default_value' => $this->options['target'],
    );

    $form['class'] = array(
      '#title' => $this->t('The class of the button'),
      '#type' => 'textfield',
      '#default_value' => $this->options['class'],
    );

    $form['text'] = array(
      '#title' => $this->t('The text of the button'),
      '#type' => 'textfield',
      '#default_value' => $this->options['text'],
    );

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

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
    return [
      '#theme'  => 'custom_button',
      '#target' => $this->options['target'],
      '#class'  => $this->options['class'],
      '#text'   => $this->options['text']
    ];
  }
}

How can I use replacement patterns in $form['text']?

1

Take a look to \Drupal\views\Plugin\views\field\FieldPluginBase::renderText

/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
  $tokens = $this->getRenderTokens($this->options['text']);
  return [
    '#theme'  => 'custom_button',
    '#target' => $this->options['target'],
    '#class'  => $this->options['class'],
    '#text'   => $this->viewsTokenReplace($this->options['text'], $tokens),
  ];
}
2
  • Thanks it works ! – sensitd Jan 13 '20 at 12:16
  • Great! Please take a moment to set the answer as correct so it will appear to others when searching. – d70rr3s Jan 13 '20 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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