0

I want to use the Element API to output a hierarchical JSON list of categories grouped by category group. For example:

{
    "groups": [
        {
            "id": 2,
            "name": "Meal Type",
            "categories": [
                {
                    "id": 284,
                    "title": "Dinner"
                },
                {
                    "id": 285,
                    "title": "Breakfast"
                }
            ]
        },
        {
            "id": 3,
            "name": "Dietary Restrictions",
            "categories": [
                {
                    "id": 291,
                    "title": "Vegan"
                },
                {
                    "id": 292,
                    "title": "Gluten Free"
                }
            ]
        }
    ]
}

But I can't figure out how to do it within the confines of the element transformer because I can't step outside of it to run some grouping logic before outputting the result. If there was some way of knowing when I've reached the end of the transformer loop then I could delay the return statement until the end of the list:

'categories.json' => function() {
    $catGroups = array();
    return [
        'elementType' => Category::class,
        'criteria' => [
            'group' => ['meal','diet'],
            'level' => 1,
            'orderBy' => 'groupId,title'
        ],
        'resourceKey' => 'groups',
        'paginate' => false,
        'transformer' => function(Category $cat) use (&$catGroups) {
            $groupExists = false;
            
            // look for existing group, add category
            // to it if found, and exit
            foreach($catGroups as $key => $group) {
                if( $group['id'] == $cat->group->id ) {
                    $catGroups[$key]['categories'][] = [
                        'id' => $cat->id,
                        'title' => $cat->title
                    ];
                    $groupExists = true;
                    break;
                }
            }

            // if group doesn't already exist,
            // create it
            if(!$groupExists) {
                $categories = [
                    'id' => $cat->id,
                    'title' => $cat->title
                ];
                $catGroups[] = [
                    'id' => $cat->group->id,
                    'name' => $cat->group->name,
                    'categories' => [$categories] 
                ];
            }

            // output entire array on final loop
            if($transformer->index == $transformer->total) {
                    return $catGroups;
            }
            return false;
        },
        'pretty' => true
    ];
},

Is this possible? Maybe using pagination somehow?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.