1

I am trying to get Products using the Element API plugin. I set the 'elementType' to Commerce_Products, CommerceProducts, etc.., but the endpoint keeps returning:

Endpoint has an invalid elementType

This is my endpoint:

use craft\commerce\elements\Product as ProductsModel;

return [
    'endpoints' => [
        'api/search' => [
            'elementType' => 'ProductsModel',
            'paginate' => false,
            'pretty' => true,
            'criteria' => [
                'limit' => 15,
                'search' => (Craft::$app->request->getParam('keyName')) ? 'title:'.'*'.Craft::$app->request->getParam('keyName').'*' : ''
            ],
            'transformer' => function(ProductsModel $product) {
                return [
                    'title' => $product->title,
                    'url' => $product->url
                ];
            },
        ],
    ]
];

How do I fix it?

2

You're so close! Just one change (see the elementType key, and the added comment)…

use craft\commerce\elements\Product;

return [
    'endpoints' => [
        'api/search' => [
            'elementType' => Product::class, // This provides Element API the fully qualified Element namespace + class.
            'paginate' => false,
            'pretty' => true,
            'criteria' => [
                'limit' => 15,
                'search' => (Craft::$app->request->getParam('keyName')) ? 'title:'.'*'.Craft::$app->request->getParam('keyName').'*' : ''
            ],
            'transformer' => function(Product $product) {
                return [
                    'title' => $product->title,
                    'url' => $product->url
                ];
            },
        ],
    ]
]

Note: I'd recommend leaving the use statement as just Product, as I've done above. What you're importing is a class that inherits from the Craft Element class… “Model” has some other specific connotations in Craft + Yii, and even though at a lower level, Elements are still models, I think it's a good idea to leave them named as-is… after all, this is the Element API! 😉

| improve this answer | |
  • 1
    For those curious folks out there, this is effectively no different than providing a string 'craft\commerce\elements\Product', but Craft 3 seems to express a pretty strong preference for the ::class constant, instead. – August Miller Dec 10 '18 at 21:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.