How to render the filter options from database table in Table Builder filter options
Created 6 years ago by srinivas214

Hi, I have table with cities (id, city name) and would like to render the cities in the below mentioned filter options by querying from the database instead of the static options. Please help me to fix this

'city' => [ 'filter' => 'select', 'options' => [ 'live' => 'Live', 'draft' => 'Draft', 'scheduled' => 'Scheduled', ], ],

ryanthompson  —  6 years ago

For the custom select FT you should just be able to make your options parameter a handler:

'options' => MyOptions::class . '@handle',

FilterInterface $filter will be available for method/class injection there:

public function handle(FilterInterface $filter, SomeRepositoryInterface $widgets) {
    return $widgets->all()->pluck('id', 'name');
}

^ Is close to a valid example I think lol

vargvinter  —  6 years ago

@ryanthompson I need this functionality too, but your sollution does not work. It just returns string 'MyOptions::class@handle' in select dropdown.

rickm  —  5 years ago

Found this whilst trying to do the same thing. Long and the short of it is that you cant do it that way. It'll give you 'Expression not allowed' errors.

The only way I've found that you can do this is to add a constructor, and populate there. An example:

Your filters:

/**
     * The table filters.
     *
     * @var array|string
     */
    protected $filters = [
        'status' => [
            'placeholder' => ' Status',
            'filter' => 'select',
            'type' => 'select',
            'query' => StatusFilterQuery::class,
            'options' => [] // <<<< LEAVE THIS AS AN EMPTY ARRAY
        ]
    ];

and the constructor:

    public function __construct(Table $table, ItemStatusRepositoryInterface $status)
    {
        parent::__construct($table);

        $this->filters['status']['options'] = $status->all()->pluck('name', 'id')->all();
    }

Feels like the wrong way to be doing this, but even setting your options to an anonymous function wont work either. On the plus side, you can add in caching to the query, so the overhead of doing it this way should be fairly negligible.

ryanthompson  —  5 years ago

The options and other handling scenarios now assume @handle so only the class is required. @rickm you can use anonymous functions for things but it has to be in a handler itself since you can't use closures in a class property. So you would have FooBarTableFilters with a handle class that would set the filters including your anonymous functions and whatever other logic you need. Hope this makes sense!