1

I have a custom entity type and a list of entities of that types shown on a standard listing page.

screenshot 1

But I need to have some filters similar to what we have on a node list page

screenshot 2

How could I do that ?

7
  • Are you familiar with the views module?
    – Eyal
    Mar 23, 2017 at 16:38
  • Could so, but seems not really. I don't see any way of using it for admin pages in D8 Mar 24, 2017 at 14:50
  • You can create a views list page for your entity type. P.S> if you'll use the same path as your current list page, it will override it.
    – Eyal
    Mar 24, 2017 at 15:25
  • How would I do that ? Mar 24, 2017 at 16:44
  • I don't know why the answer was deleted. It was actually the correct, related answer, just a bit short. The node list is a view. The by far easiest option is to add views integration by specifying the views_data handler on the entity type, see examples in core and create a view.
    – Berdir
    Mar 24, 2017 at 22:51

1 Answer 1

2

Yes, everybody keeps mentioning Views. But it can be done easily without Views.

Basically, you need, in addition to your EntityListBuilder, a form that will expose the filter. Just create a usual form extending FormBase, building whatever UI you need (eg. a dropdown with items to select from, and a Filter submit button).

Your list builder will first create that form and then use it together with the rendered entity list:

public function render() {
  $build['form'] = \Drupal::formBuilder()->getForm('Drupal\your_module\Form\YourFilterForm');
  $build += parent::render();
  return $build;
}

In the submit handler of the form, you redirect to the same URL but with the filter query variables added:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $value = $form_state->getValue('your_var_name');
  $query = ['your_var_name' => $value];
  $form_state->setRedirect('route_name_of_your_entity_list', $query);
}

Also, if you want a Reset button, just do the same redirect without the query, thus clearing it.

In your entity list builder, you have a getEntityIds() that's responsible for loading the entities. You probably didn't override it at all to get the full list. But you can override, get the current filter and only load those matching the filter:

protected function getEntityIds() {
  $value = \Drupal::request()->get('your_var_name');
  $query = \Drupal::entityQuery($this->entityTypeId);
  $query->condition('your_var_name', $value);
  return $query->execute();
}

Or, if there is no actual filter, just call the original parent::getEntityIds();.

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