Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Apply a default sort configuration based on a filter scope value

0
by LukeTowers, last modified on May 3rd, 2025

Add the following code in your backend controller class to apply a default sort configuration to your list based on the value selected in a given filter scope:

    public function listFilterExtendScopes(Filter $filterWidget)
    {
        $getSortConfig = function (Filter $filter) {
            $currentStatus = $filter->getScopeValue('status') ?? $filter->scopes['status']['default'];
            $defaultSorts = [
                'upcoming' => [
                    'column' => 'start_date',
                    'direction' => 'asc',
                ],
                'completed' => [
                    'column' => 'start_date',
                    'direction' => 'desc',
                ],
            ];

            return $defaultSorts[$currentStatus];
        };

        // Apply default sort column / direction logic based on the selected status filter
        $this->listGetWidget()->defaultSort = $getSortConfig($filterWidget);

        // Apply default sort config when updating the status filter
        $filterWidget->bindEvent('filter.update', function () use ($filterWidget, $getSortConfig) {
            if (post('scopeName') === 'status') {
                $sort = $getSortConfig($filterWidget);
                $this->listGetWidget()->setSort($sort['column'], $sort['direction']);
            }
        }, 1);
    }

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?