CodeWithDennis / filament-select-tree

The multi-level select field lets you pick one or multiple options from a list that is neatly organized into different levels.
MIT License
225 stars 33 forks source link

Usage in filters ? #32

Closed ThisIsMyFavouriteJar closed 12 months ago

ThisIsMyFavouriteJar commented 1 year ago

Hello,

Love this plugin! I managed to get this working as a filter as well, only closing an indicator does not feed back to the selected values.

So if I close the active filter (by clicking the X), the values are still displayed in the categories field.

image

(They are correctly linked, active filters showing the ID instead of the name.)

I tried several thing, but did not manage to get it to work. Any thoughts on this?

CodeWithDennis commented 1 year ago

That's great to hear you're enjoying the plugin! I never thought about using it as a filter before; that's a clever idea.

Since you've mentioned having to use some workaround to make it function, I'm considering creating a TreeSelectFilter class that can handle everything seamlessly.

I'll keep you in the loop and update this issue as I make progress.

CodeWithDennis commented 12 months ago

Hey, sorry for the wait! I think I've got a solution for your problem. It involves making some queries to the database when using filters, but I don't think it'll be a big performance problem. Here's a quick snippet of what I came up with. I'll be adding this to the documentation.

->filters([
    Filter::make('tree')
        ->form([
            SelectTree::make('categories')
                ->relationship('categories', 'name', 'parent_id')
                ->independent(false)
                ->enableBranchNode(),
        ])
        ->query(function (Builder $query, array $data) {
            return $query->when($data['categories'], function ($query, $categories) {
                return $query->whereHas('categories', fn($query) => $query->whereIn('id', $categories));
            });
        })
        ->indicateUsing(function (array $data): ?string {
            if (! $data['categories']) {
                return null;
            }

            return __('Categories') . ': ' . implode(', ', Category::whereIn('id', $data['categories'])->get()->pluck('name')->toArray());
        })
])
CodeWithDennis commented 12 months ago

Let me know if this solved your problem. @ThisIsMyFavouriteJar

ThisIsMyFavouriteJar commented 11 months ago

Hi Dennis, Thank you for this update, looks good!