Filter Menu with multiple Category-Tags for each Project (Multiselect)

Hey hey,

I am using a filter menu to provide an easy way for people to find projects within there area of interest. Some projects have multiple categories. Can someone help me applying that on my filter?

The absolute optimum would be to have the option to select several categories in the filter and then all projects are displayed that contain at least one of the entered categories. Is that possible?

This is the code im using right now for the filter (without multiselect) …

$filterBy = get ('filter');
$unfiltered = $page
	->children()
	->listed();
$projects = $unfiltered
	->when($filterBy, function($filterBy) {
		return $this->filterBy('category', $filterBy);
	});

$filters = $unfiltered->pluck('category', ',', true);

… and this the code for the filter buttons.

<div class="filter">

	<div class="reset-filters">
		<a href="<?= $page->url() ?>">Reset Filters</a>
	</div>

	<?php foreach ($filters as $filter): ?>
	<a class="<?= $filterBy === $filter ? 'active' : '' ?>"
		href="<?= $page->url() ?>?filter=<?= $filter ?>">
		<?= $filter ?>
	</a>
	<?php endforeach ?>

</div>

Thank you very much, Simon

You need to pass a separator as argument for the filter to work with (comma) separated values:

$projects = $unfiltered
	->when($filterBy, function($filterBy) {
		return $this->filterBy('category', $filterBy, ',');
	});
1 Like

Thank you – that works!

Do you have an idea how can make it possible to select multiple filter items that make me see all projects that contain at least one of the entered categories?

Have a nice evening, Simon

There are two parts to it:

  1. You need to provide an array of values in your query string, it has to look something like this ?cars[]=Saab&cars[]=Audi
  2. Then get('cars') will give you an array of values which you can use in your filter like before with only a small change:
$projects = $unfiltered
	->when($filterBy, function($filterBy) {
		return $this->filterBy('category', 'in', $filterBy);
	});

When creating your links with the query string, you would then have to make sure that you adapt the urls to respect already existing filters, otherwise, each click on a link removes the already selected value. Might be a better option to handle this via a form.