1

Background

I've built a custom entity using the drupal console, which was kind enough to implement an instance of EntityViewsData for my entity, called MyEntityViewsData.

In the call to MyEntityViewsData::getViewsData(), I have successfully registered a dynamic field, which I then implemented by extending FieldPluginBase. This works as intended.

I then tried the same approach to implement sorting for this field (this time extending SortPluginBase), but have not had any success. I also tried just using the Standard (Drupal\views\Plugin\views\field\Standard) sort plugin. But every attempt results in a SQL error that the sort field does not exist.

The question

How do I sort a dynamic field in Views?

Code

src/Entity/MyEntityViewsData.php

class MyEntityViewsData extends EntityViewsData implements EntityViewsDataInterface {

  /**
   * {@inheritdoc}
   */
  public function getViewsData() {
    $data = parent::getViewsData();
    $table = &$data['myentity_field_data'];
    $table['display_name'] = [
      'title' => $this->t('Display name'),
      'field' => [
        'title' => $this->t('Display name'),
        'help' => $this->t('Displays the entity's Short Name if available, or the Name otherwise.'),
        'id' => 'myentity_display_name_field',
      ],

     'sort' => [

        // Results in SQL error...
        'title' => $this->t('Display name'),
        'help' => $this->t('Sorts entities by display name.'),
        'id' => 'myentity_display_name_sort',

        // Also results in SQL error.
        'field' => 'display_name',
        'id' => 'standard',
      ]
    ];
    return $data;
  }

}

src/Plugin/views/field/MyEntityDisplayNameField.php

/**
 * @ViewsField("myentity_display_name_field");
 */
class MyEntityDisplayNameField extends FieldPluginBase {
  public function query() {
    // Nothing to return.
  }

  public function render(ResultRow $values) {
    $my_entity = $this->getEntity($values);
    return $my_entity->getDisplayName();
  }
}

src/Plugin/views/sort/MyEntityDisplayNameSort.php

/**
 * @ViewsSort("myentity_display_name_sort")
 */
class MyEntityDisplayNameSort extends SortPluginBase {
  public function query() {
    $this->ensureMyTable();

    // This results in an error...
    $this->query->addOrderBy(NULL, "{$this->tableAlias}.{$this->realField}", $this->options['order'], $this->tableAlias.'_display_name_sort');

    // As does this.
    $this->query->orderby[] = [
      'field' => "{$this->tableAlias}.{$this->realField}",
      'direction' => $this->options['order'],
    ];
  }
}

Your Answer

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

Browse other questions tagged or ask your own question.