Text Filtering Relationships
- Posted April 11, 2018
- Developer Tools
- filters
- tables
- ui
Related Links
By default relationships in Pyro are filtered using an automated dropdown where the dropdown text is the related stream's title_column
and the value is the id
of the related entry. This is because relations are stored as a native Laravel relationship and thus have a related_field_id
column.
In order to implement text search filtering for relations on a table builder you will need to implement a very simple custom filter. Let's take a look at an example that filters created_by
users by username or email.
Define Your Filter
We will use a generic input
filter so let's first define that on the table builder we are developing:
protected $filters = [
'user' => [
'filter' => 'input',
'placeholder' => 'User',
'query' => UserFilterQuery::class,
],
];
For more information on filter definitions take a look at our documentation on the filters.
All that is left now is the query class that handles the input from this filter!
Define The Query Handler
In this case we want the query handler to join
the users table and use our filter value
to restrict the query using where
clauses. Just like other handlers in Laravel we only need to define the handle
method and use the passed $query
and $filter
instance which are the table's query builder and the instance of the custom filter object respectively.
<?php namespace ExampleCompany\ExampleModule\Example\Table\Filter;
use Anomaly\Streams\Platform\Ui\Table\Component\Filter\Contract\FilterInterface;
use Illuminate\Database\Eloquent\Builder;
class UserFilterQuery
{
public function handle(Builder $query, FilterInterface $filter)
{
$query->join('users_users', 'example_table.created_by_id', '=', 'users_users.id');
$query->where('username', 'LIKE', '%' . $filter->getValue() . '%');
$query->orWhere('email', 'LIKE', '%' . $filter->getValue() . '%');
}
}
That's it! You now have a custom text search input.