Search code examples
sulu

sulu 2.2: Ist there a way that categories in the category_selection content type are sorted automatically by name?


Is there a way that the displayed categories of the category_selection content type are sorted by name rather then id? They are loaded via ajax from the api like http://localhost:8000/admin/api/categories?locale=de&selectedIds=7&fields=name,id&flat=true

If there is a stable way to add a sort like in the category overview, it would be a great addition.


Solution

  • There is no way to sort them out of the box alphabetically.

    But you can override the CategoryController and add $listBuilder->sort($fieldDescriptors['name']); after the initializeListBuilder call in the getListRepresentation method.

    Edit: I just found out, that we need a default sort order anyway, otherwise the result order can differ between two identical request. I created a pull request with the changes https://github.com/sulu/sulu/pull/6136

    Until this fix is released, you can just override your CategoryController and add the sorting manually.

    Edit2: How to override the Controller:

    First you have to create your own Controller and extend from the CategoryController and override the specific method e.g.:

    class CustomCategoryController extends SuluCategoryController
    {
    protected function getListRepresentation(
        Request $request,
        $locale,
        $parentId = null,
        $expandedIds = [],
        $expandSelf = false,
        $includeRoot = false
    ) {
        $listBuilder = $this->initializeListBuilder($locale);
         <add default sort here>
         <copy the rest of the original function here>
        }
    }
    

    The second step is to add this service to the services.yaml file and add an alias to override the original CategoryController:

    App\Controller\Admin\CustomCategoryController:
        alias: sulu_category.category_controller