1

Is it possible to get a list of category groups without having to loop through all categories to get their parent group name?

UPDATE:

Just making this question clearer, as it's related to using elementapi. Ideally, I'd like to get a list of category groups via elementapi.

This is what I currently have:

'api/menu' => function() {
  return [
    'elementType' => ElementType::Category,
    'paginate' => false,
    'criteria' => [
      'group' => ['stages', 'series', 'disciplines'],
      'limit' => null,
      'with' => ['group']
    ],
    'transformer' => function(CategoryModel $category) {

      $group = $category->group ?? null;

      return [
        'id' => (int)$category->id,
        'title' => $category->title,
        'slug' => $category->slug,
        'summary' => $category->summary,
        'group' => [
          'id' => (int)$group->id,
          'handle' => (string)$group->handle,
          'name' => (string)$group->name
        ]
      ];
    }
  ];
},

I'd want to structure the data by categorygroup rather than cateogries, something like this (it doesn't work because CategoryGroup is not an elementType) but wondering if there is another way to get the same result?:

'api/menu' => function() {
    return [
      'elementType' => ElementType::CategoryGroup,
      'paginate' => false,
      'limit' => null
    ],
    'transformer' => function(CategoryGroupModel $categoryGroup) {

      $categories = craft()->elements->getCriteria(ElementType::Category)->group($categoryGroup->handle);

      $cats = [];
      foreach($categories as $category) {
        $cats[] = [
          'id' => (int)$category->id,
          'title' => $category->title,
          'slug' => $category->slug
        ];
      }

      return [
        'id' => (int)$categoryGroup->id,
        'title' => $categoryGroup->name,
        'handle' => $categoryGroup->handle,
        'categories' => $cats
    }
  ];
},
  • 1
    What about craft()->categories->getAllGroups()? – Robin Schambach Nov 20 '17 at 13:06
  • @RobinSchambach thanks for the quick answer! That will get me all the groups in a template, however, I'm having trouble getting category groups via elementapi, I've updated my question to be more specific. – samput Nov 20 '17 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.