Pagination and Sorting with Commerce Backends

When implementing a Pagination on your side using commercetools (or maybe another backend), you may see some products are displayed twice on different Pages. The reason for this is pretty simple: If you don't provide sorting to the Commerce backend while implementing a Pagination, the results you get back will be randomly sorted.

But don't worry we've got you covered and this article will explain how to prevent such cases from happening with Frontastic.

When you implement a Pagination with our Streams, you'll need to modify the offset parameter of the Stream and therefore switch through the Pages. When no Sorting is given - as is the Default - the Commerce backends may return the Products randomly ordered. This may lead to a Product showing up on Page one but also on Page three or any other one Page.

You can prevent this by setting a Default Sorting using our API Decorators.

For listing Products, the query() method on the Product API should be used, so we'll need to implement a beforeQuery() Decorator that sets the Default Sorting according to your needs on the ProductQuery before the query is actually executed.

Let's have a look at this short example:

<?php

namespace YourCustomerNamespace\ProductBundle\Domain;

use Frontastic\Common\ProductApiBundle\Domain\ProductApi;

class DefaultProductSortOrder
{
    public function beforeQuery(ProductApi $productApi, ProductApi\Query\ProductQuery $query): void
    {
        if (isset($query->query)) {
            // Don't change sort order in real searches
            return;
        }

        if (!$query->sortAttributes) {
            $query->sortAttributes = [
                'variants.attributes.popularity' => ProductApi\Query\ProductQuery::SORT_ORDER_DESCENDING,
                'variants.availability.availableQuantity' => ProductApi\Query\ProductQuery::SORT_ORDER_DESCENDING,
                'variants.attributes.brand_value' => ProductApi\Query\ProductQuery::SORT_ORDER_ASCENDING,
            ];
        }

        // Ensure we always get a deterministic sort order
        $query->sortAttributes += [
            'variants.sku' => ProductApi\Query\ProductQuery::SORT_ORDER_ASCENDING,
        ];
    }
}

This example will ignore searches where the query parameter is set and if no sortAttributes are set it will set the Default ones. By Default it'll also always add a sorting by sku to get deterministic results.

TIP: Be sure to name your file the same as your ClassName, so in this example it would be:DefaultProductSortOrder.php.

Feel free to adapt this example to your needs and add to your code base but you may need to adjust it to your actual available properties.

Don't forget to source the Decorator properly as described in the API Decorators article.


‹ Back to Article List

Next Article ›

Loaders in the Frontend Frameworks

Still need help? Contact Us Contact Us