I have a custom entity type and a list of entities of that types shown on a standard listing page.
But I need to have some filters similar to what we have on a node list page
How could I do that ?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI have a custom entity type and a list of entities of that types shown on a standard listing page.
But I need to have some filters similar to what we have on a node list page
How could I do that ?
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();
.