2

I am having trouble getting the related category passed thru to the entry api endpoint.

I cant use :

   $criteria = craft()->elements->getCriteria(ElementType::Category);
        $criteria->id = $catId;
        $category = $criteria->first();

What is the equivalent in craft 3 api v2?

'api/v1/ship/category/<catId:\d+>.json' => function($catId) {
//old api craft 2
        $criteria = craft()->elements->getCriteria(ElementType::Category);
        $criteria->id = $catId;
        $category = $criteria->first();

//api craft 3
        return [
            'elementType' => Entry::class,
            'elementsPerPage' => 30,
            'criteria' => [
                'criteria' => ['section' => 'ship'],
                'relatedTo' => ['targetElement' => $category],
            ],
            'transformer' => function(Entry $entry) {
                return [
                    'title' => $entry->title,
                    'id' => (int) $entry->id,
                    'slug' => $entry->slug,
                    'postDate' => $entry->postDate
                ];
            },
            'pretty' => true
        ];
    },
joomkit
  • 2,014
  • 1
  • 13
  • 24

1 Answers1

1

Solved it like this:

//categories
    'api/v1/ship/category/<catId:\d+>.json' => function($catId) {
        return [
            'elementType' => Category::class,
            'criteria'    => ['id'   => $catId],
            'paginate'    => false,
            'transformer' => function(Category $category) {
                $entries = Entry::find()->relatedTo($category)->all();

                $en=[];
                foreach($entries as $entry) {


                    //Final return
                    $en[]= [
                        "type" => "shipItem",
                        'sendtoseafarerhelp' => $entry->sendToSeafarerHelp,
                        'title' => $entry->title,
                        'url' => $entry->url,
                        'categoryTitle' => $entry->shipCategory[0]->title,
                        'categorySlug' => $entry->shipCategory[0]->slug,
                        'categoryUrl' => $entry->shipCategory[0]->uri,
                        'summary' => $entry->shipIntroText,
                        'descripton' => $entry->shipDescription,
                        'pdfs' => $pdfs,
                        'thumbs' => $thumbs,
                        'sponsors' => $sponsors                            
                    ];
                }

                return [
                    'title'   => $category->title,
                    'entries' => $en
                ];
            }
        ];
    },
joomkit
  • 2,014
  • 1
  • 13
  • 24
  • joomkit: $entries = Entry::find()->relatedTo($category)->all(); Doesn't return any entries though I have two entries on the same Category. Is there any specific way a Category should be assigned to an Entry? – Wasantha Wijayaratna May 12 '19 at 04:14