0

On Craft, I can assign categories to my different customers: a customer might be "Cloud", "Software" or "Energy". I have set it up so that you can also choose subcategories (children) ("Cloud subcat 1", "Cloud subcat 2", "Energy subcat 1").

Cloud
--- Cloud subcat 1
--- Cloud subcat 2
Software
Energy
--- Energy subcat 1

The customer entry can have multiple categories or subcategories selected, and choosing a parent category (ex Cloud) does not mean that it's children are necessarily selected.

I'm trying to pull this data using Element API. This is what I have set up:

        'transformer' => function(Entry $entry){
          foreach ($entry->customerType->level(1)->all() as $cat) { // to only pull parent-level categories
            $data[$cat->title] = [];
            $children = $cat->getChildren();
            if ($children) {
                $data[$cat->title]['category'] = [];
                foreach ($children as $child) {
                    $data[$cat->title]['category'][] = $child->title;
                }
            }
          }
    ...
    return [ 
    'searchableFields' => [
      'category' => (array) $data
]
    ]

When I pull the customer data on the front end though, any customer that has "Cloud" selected as the category also has "Cloud subcat 1" and "Cloud subcat 2" assigned as subcategories, even though those weren't selected in the admin. I would want that customer to just be [Cloud], not [Cloud: Cloud subcat 1, Cloud subcat 2]. Am I missing something in the PHP? Is this even possible?

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.