Magento2: Position sort does not work in GraphQl.

Created on 11 Feb 2020  路  22Comments  路  Source: magento/magento2

Preconditions (*)

  1. Magento 2.3.4 Open Source

Steps to reproduce (*)

  1. Install demo data
  2. Assign positions to all products in the Watches category (id: 6)
    Screenshot from 2020-02-11 16-31-53
  3. Run the following GraphQl Query.
query category {
  categoryList(
    filters: {ids: {eq: "6"}}
  ) {
    products(
      sort: {
        position: ASC
      }
    ) {
      items {
        id
      }
      total_count
    }
  }
}

Expected result (*)

{
    "data": {
        "categoryList": [
            {
                "products": {
                    "items": [
                        {
                            "id": 43
                        },
                        {
                            "id": 41
                        },
                        {
                            "id": 39
                        },
                        {
                            "id": 37
                        },
                        {
                            "id": 36
                        },
                        {
                            "id": 38
                        },
                        {
                            "id": 40
                        },
                        {
                            "id": 42
                        },
                        {
                            "id": 44
                        }
                    ],
                    "total_count": 9
                }
            }
        ]
    }
}

Actual result (*)

{
    "data": {
        "categoryList": [
            {
                "products": {
                    "items": [
                        {
                            "id": 36
                        },
                        {
                            "id": 37
                        },
                        {
                            "id": 38
                        },
                        {
                            "id": 39
                        },
                        {
                            "id": 40
                        },
                        {
                            "id": 41
                        },
                        {
                            "id": 42
                        },
                        {
                            "id": 43
                        },
                        {
                            "id": 44
                        }
                    ],
                    "total_count": 9
                }
            }
        ]
    }
}
CatalogGraphQl GraphQL Fixed in 2.4.x Clear Description Confirmed Format is valid Ready for Work Reported on 2.3.4 Reproduced on 2.4.x

Most helpful comment

I'm using magento 2.3.5-p1, and this is how i fixed it based on @radub and @Hexmage answers and using magento plugins:

in Vendor/etc/di.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch">
        <plugin name="vendor_category_product_search_after" type="Vendor\CategoryProductsSortFix\Plugin\BeforeProductSearch"/>
    </type>
    <type name="Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CompositeCollectionProcessor">
        <arguments>
            <argument name="collectionProcessors" xsi:type="array">
                <item name="joinCatalogCategoryProductForPosition" xsi:type="object">
                    Vendor\CategoryProductsSortFix\Model\Resolver\Products\DataProvider\CatalogCategoryProductJoinProcessor
                </item>
            </argument>
        </arguments>
    </type>
</config>

in Vendor/CategoryProductsSortFix/Model/Resolver/Products/DataProvider/CatalogCategoryProductJoinProcessor.php:

<?php

namespace Vendor\CategoryProductsSortFix\Model\Resolver\Products\DataProvider;

use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CollectionProcessorInterface;
use Magento\Framework\Api\SearchCriteriaInterface;

/**
 * Class CatalogCategoryProductJoinProcessor
 */
class CatalogCategoryProductJoinProcessor implements CollectionProcessorInterface
{
    /**
     * @param Collection $collection
     * @param SearchCriteriaInterface $searchCriteria
     * @param array $attributeNames
     * @return Collection
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function process(
        Collection $collection,
        SearchCriteriaInterface $searchCriteria,
        array $attributeNames
    ): Collection {
        if ($categoryFilter = $this->getFilterByFieldName($searchCriteria, 'category_id')) {
            try {
                $collection->joinField(
                    'position',
                    'catalog_category_product',
                    'position',
                    'product_id=entity_id',
                    '{{table}}.category_id IN (' . $categoryFilter->getValue() . ')',
                    'inner'
                );
            } catch (LocalizedException $e) {
                // join already exists
                return $collection;
            }
        }

        return $collection;
    }

    /**
     * @param SearchCriteriaInterface $searchCriteria
     * @param $fieldName
     * @return Filter|null
     */
    private function getFilterByFieldName(SearchCriteriaInterface $searchCriteria, $fieldName)
    {
        foreach ($searchCriteria->getFilterGroups() as $filterGroup) {
            /** @var Filter $filter */
            foreach ($filterGroup->getFilters() as $filter) {
                if ($filter->getField() === $fieldName) {
                    return $filter;
                }
            }
        }

        return null;
    }
}

in Vendor\CategoryProductsSortFix\Plugin\BeforeProductSearch.php:

<?php

namespace Vendor\CategoryProductsSortFix\Plugin;

use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Api\SearchCriteriaInterface;

/**
 * Class BeforeProductSearch
 * @package Vendor\CategoryProductsSortFix\Plugin
 */
class BeforeProductSearch
{
    /**
     * @param \Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch $productSearch
     * @param SearchCriteriaInterface $searchCriteria
     * @param SearchResultInterface $searchResult
     * @param array $attributes
     * @return array
     */
    public function beforeGetList(
        \Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch $productSearch,
        SearchCriteriaInterface $searchCriteria,
        SearchResultInterface $searchResult,
        array $attributes = []
    ) {
        $filterGroup = $searchResult->getSearchCriteria()->getFilterGroups()[0];
        if ($filterGroup->getFilters()[0]->getField() == 'category_id') {
            $searchCriteria->setFilterGroups([$filterGroup]);
        }
        return [$searchCriteria, $searchResult, $attributes];
    }
}

All 22 comments

Hi @Hexmage. Thank you for your report.
To help us process this issue please make sure that you provided the following information:

  • [ ] Summary of the issue
  • [ ] Information on your environment
  • [ ] Steps to reproduce
  • [ ] Expected and actual results

Please make sure that the issue is reproducible on the vanilla Magento instance following Steps to reproduce. To deploy vanilla Magento instance on our environment, please, add a comment to the issue:

@magento give me 2.4-develop instance - upcoming 2.4.x release

For more details, please, review the Magento Contributor Assistant documentation.

@Hexmage do you confirm that you were able to reproduce the issue on vanilla Magento instance following steps to reproduce?

  • [ ] yes
  • [ ] no

It looks like the issue is caused by the products collection not having been joined with the catalog_category_position table. Because it can't find the category position it falls back onto entity_id.

@magento give me 2.4-develop instance - upcoming 2.4.x release

Hi @Hexmage. Thank you for your request. I'm working on Magento 2.4-develop instance for you

Hi @Hexmage, here is your Magento instance.
Admin access: https://i-26817-2-4-develop.instances.magento-community.engineering/admin_fcea
Login: 138cdecc Password: 3b27a7255b44
Instance will be terminated in up to 3 hours.

Confirmed to not work on 2.4-develop

Hi @shikhamis11. Thank you for working on this issue.
In order to make sure that issue has enough information and ready for development, please read and check the following instruction: :point_down:

  • [ ] 1. Verify that issue has all the required information. (Preconditions, Steps to reproduce, Expected result, Actual result).
    DetailsIf the issue has a valid description, the label Issue: Format is valid will be added to the issue automatically. Please, edit issue description if needed, until label Issue: Format is valid appears.
  • [ ] 2. Verify that issue has a meaningful description and provides enough information to reproduce the issue. If the report is valid, add Issue: Clear Description label to the issue by yourself.

  • [ ] 3. Add Component: XXXXX label(s) to the ticket, indicating the components it may be related to.

  • [ ] 4. Verify that the issue is reproducible on 2.4-develop branch

    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and _stop verification process here_!

  • [ ] 5. Add label Issue: Confirmed once verification is complete.

  • [ ] 6. Make sure that automatic system confirms that report has been added to the backlog.

This used to work on 2.3.3, if you manually added position to the graphql.schema for ProductSortInput, but it looks like the new filter/ search system has broken this.

Hi @engcom-Bravo. Thank you for working on this issue.
In order to make sure that issue has enough information and ready for development, please read and check the following instruction: :point_down:

  • [ ] 1. Verify that issue has all the required information. (Preconditions, Steps to reproduce, Expected result, Actual result).
    DetailsIf the issue has a valid description, the label Issue: Format is valid will be added to the issue automatically. Please, edit issue description if needed, until label Issue: Format is valid appears.
  • [ ] 2. Verify that issue has a meaningful description and provides enough information to reproduce the issue. If the report is valid, add Issue: Clear Description label to the issue by yourself.

  • [ ] 3. Add Component: XXXXX label(s) to the ticket, indicating the components it may be related to.

  • [ ] 4. Verify that the issue is reproducible on 2.4-develop branch

    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and _stop verification process here_!

  • [ ] 5. Add label Issue: Confirmed once verification is complete.

  • [ ] 6. Make sure that automatic system confirms that report has been added to the backlog.

:white_check_mark: Confirmed by @engcom-Bravo
Thank you for verifying the issue. Based on the provided information internal tickets MC-31477 were created

Issue Available: @engcom-Bravo, _You will be automatically unassigned. Contributors/Maintainers can claim this issue to continue. To reclaim and continue work, reassign the ticket to yourself._

Doing the following resolves the issue, but it isn't a nice/good solution. This adds the category filterGroup to the searchCriteria, because position sort requires a join on the category index.

\Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch::getList

/**
     * Get list of product data with full data set. Adds eav attributes to result set from passed in array
     *
     * @param SearchCriteriaInterface $searchCriteria
     * @param SearchResultInterface $searchResult
     * @param array $attributes
     * @return SearchResultsInterface
     */
    public function getList(
        SearchCriteriaInterface $searchCriteria,
        SearchResultInterface $searchResult,
        array $attributes = []
    ): SearchResultsInterface {

+       $filterGroup = $searchResult->getSearchCriteria()->getFilterGroups()[0];
+       $searchCriteria->setFilterGroups([$filterGroup]);

        /** @var Collection $collection */
        $collection = $this->collectionFactory->create();

        //Join search results
        $this->getSearchResultsApplier($searchResult, $collection, $this->getSortOrderArray($searchCriteria))->apply();

        $this->collectionPreProcessor->process($collection, $searchCriteria, $attributes);
        $collection->load();
        $this->collectionPostProcessor->process($collection, $attributes);

        $searchResults = $this->searchResultsFactory->create();
        $searchResults->setSearchCriteria($searchCriteria);
        $searchResults->setItems($collection->getItems());
        $searchResults->setTotalCount($searchResult->getTotalCount());
        return $searchResults;
    }

Hi @nrkapoor. Thank you for working on this issue.
Looks like this issue is already verified and confirmed. But if you want to validate it one more time, please, go though the following instruction:

  • [ ] 1. Add/Edit Component: XXXXX label(s) to the ticket, indicating the components it may be related to.
  • [ ] 2. Verify that the issue is reproducible on 2.4-develop branch

    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and _stop verification process here_!

  • [ ] 3. If the issue is not relevant or is not reproducible any more, feel free to close it.


Hi @shikhamis11. Thank you for working on this issue.
Looks like this issue is already verified and confirmed. But if you want to validate it one more time, please, go though the following instruction:

  • [ ] 1. Add/Edit Component: XXXXX label(s) to the ticket, indicating the components it may be related to.
  • [ ] 2. Verify that the issue is reproducible on 2.4-develop branch

    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and _stop verification process here_!

  • [ ] 3. If the issue is not relevant or is not reproducible any more, feel free to close it.


Thank you for reporting this issue. I have created an internal JIRA item and will address this issue as part of the 2.4 release. I will update the issue once the fix is available in 2.4 development.

Hi @cpartica. Thank you for working on this issue.
Looks like this issue is already verified and confirmed. But if you want to validate it one more time, please, go though the following instruction:

  • [ ] 1. Add/Edit Component: XXXXX label(s) to the ticket, indicating the components it may be related to.
  • [ ] 2. Verify that the issue is reproducible on 2.4-develop branch

    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and _stop verification process here_!

  • [ ] 3. If the issue is not relevant or is not reproducible any more, feel free to close it.


Thanks for your contribution. We started working on this internally.

@Hexmage the workaround (https://github.com/magento/magento2/issues/26817#issuecomment-591429899) worked on M2.3.4 but is no longer working on M2.3.5 - I'm looking into it as M2.4 is really far away.

vendor/magento/module-catalog-graph-ql/Model/Resolver/Products/Query/Search.php has changed in 2.3.5

@Hexmage I've made your workaround work on M2.3.5 as well by creating the following collection processor and injected it at the end of the already existing 7 collection processors which are being executed before collection load (\Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider +91). For some reason the join with the category_catalog_product table was no longer made just by setting the company_id filter in $searchCriteria.

namespace MyModule\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CollectionProcessor;

/**
 * Class CatalogCategoryProductJoinProcessor
 */
class CatalogCategoryProductJoinProcessor implements CollectionProcessorInterface
{
    /**
     * @param Collection $collection
     * @param SearchCriteriaInterface $searchCriteria
     * @param array $attributeNames
     * @return Collection
     */
    public function process(
        Collection $collection,
        SearchCriteriaInterface $searchCriteria,
        array $attributeNames
    ): Collection {
        if ($categoryFilter = $this->getFilterByFieldName($searchCriteria, 'category_id')) {
            try {
                $collection->joinField(
                    'position',
                    'catalog_category_product',
                    'position',
                    'product_id=entity_id',
                    '{{table}}.category_id IN ('. $categoryFilter->getValue() .')',
                    'inner'
                );
            } catch (LocalizedException $e) {
                // join already exists
                return $collection;
            }
        }

        return $collection;
    }

    /**
     * @param SearchCriteriaInterface $searchCriteria
     * @param $fieldName
     * @return Filter|null
     */
    private function getFilterByFieldName(SearchCriteriaInterface $searchCriteria, $fieldName)
    {
        foreach ($searchCriteria->getFilterGroups() as $filterGroup) {
            /** @var Filter $filter */
            foreach ($filterGroup->getFilters() as $filter) {
                if ($filter->getField() === $fieldName) {
                    return $filter;
                }
            }
        }

        return null;
    }
}

and the etc/di.xml file

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CompositeCollectionProcessor">
        <arguments>
            <argument name="collectionProcessors" xsi:type="array">
                <item name="joinCatalogCategoryProductForPosition" xsi:type="object">
                    MyModule\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CollectionProcessor\CatalogCategoryProductJoinProcessor
                </item>
            </argument>
        </arguments>
    </type>
</config>

I'm using magento 2.3.5-p1, and this is how i fixed it based on @radub and @Hexmage answers and using magento plugins:

in Vendor/etc/di.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch">
        <plugin name="vendor_category_product_search_after" type="Vendor\CategoryProductsSortFix\Plugin\BeforeProductSearch"/>
    </type>
    <type name="Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CompositeCollectionProcessor">
        <arguments>
            <argument name="collectionProcessors" xsi:type="array">
                <item name="joinCatalogCategoryProductForPosition" xsi:type="object">
                    Vendor\CategoryProductsSortFix\Model\Resolver\Products\DataProvider\CatalogCategoryProductJoinProcessor
                </item>
            </argument>
        </arguments>
    </type>
</config>

in Vendor/CategoryProductsSortFix/Model/Resolver/Products/DataProvider/CatalogCategoryProductJoinProcessor.php:

<?php

namespace Vendor\CategoryProductsSortFix\Model\Resolver\Products\DataProvider;

use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CollectionProcessorInterface;
use Magento\Framework\Api\SearchCriteriaInterface;

/**
 * Class CatalogCategoryProductJoinProcessor
 */
class CatalogCategoryProductJoinProcessor implements CollectionProcessorInterface
{
    /**
     * @param Collection $collection
     * @param SearchCriteriaInterface $searchCriteria
     * @param array $attributeNames
     * @return Collection
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function process(
        Collection $collection,
        SearchCriteriaInterface $searchCriteria,
        array $attributeNames
    ): Collection {
        if ($categoryFilter = $this->getFilterByFieldName($searchCriteria, 'category_id')) {
            try {
                $collection->joinField(
                    'position',
                    'catalog_category_product',
                    'position',
                    'product_id=entity_id',
                    '{{table}}.category_id IN (' . $categoryFilter->getValue() . ')',
                    'inner'
                );
            } catch (LocalizedException $e) {
                // join already exists
                return $collection;
            }
        }

        return $collection;
    }

    /**
     * @param SearchCriteriaInterface $searchCriteria
     * @param $fieldName
     * @return Filter|null
     */
    private function getFilterByFieldName(SearchCriteriaInterface $searchCriteria, $fieldName)
    {
        foreach ($searchCriteria->getFilterGroups() as $filterGroup) {
            /** @var Filter $filter */
            foreach ($filterGroup->getFilters() as $filter) {
                if ($filter->getField() === $fieldName) {
                    return $filter;
                }
            }
        }

        return null;
    }
}

in Vendor\CategoryProductsSortFix\Plugin\BeforeProductSearch.php:

<?php

namespace Vendor\CategoryProductsSortFix\Plugin;

use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Api\SearchCriteriaInterface;

/**
 * Class BeforeProductSearch
 * @package Vendor\CategoryProductsSortFix\Plugin
 */
class BeforeProductSearch
{
    /**
     * @param \Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch $productSearch
     * @param SearchCriteriaInterface $searchCriteria
     * @param SearchResultInterface $searchResult
     * @param array $attributes
     * @return array
     */
    public function beforeGetList(
        \Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\ProductSearch $productSearch,
        SearchCriteriaInterface $searchCriteria,
        SearchResultInterface $searchResult,
        array $attributes = []
    ) {
        $filterGroup = $searchResult->getSearchCriteria()->getFilterGroups()[0];
        if ($filterGroup->getFilters()[0]->getField() == 'category_id') {
            $searchCriteria->setFilterGroups([$filterGroup]);
        }
        return [$searchCriteria, $searchResult, $attributes];
    }
}

@khaled-badenjki We've used the position sort solution for 2.3.4-p1 and have found that the value entered changes after saving - usually as if there's a multiplier being applied, but occasionally resulting in a negative value. Any insight?

I'm also curious if anyone has managed to apply the position sorting fix to the carousel product sliders as well?

Solution provided by @khaled-badenjki works correctly only if you are not using anchor categories.
To fix the problem, change join type from inner to left in CatalogCategoryProductJoinProcessor.php class.

Also, join is added on every page load even if products are not sorted by position. To fix, add sorting statement in separate method in same class:

/**
 * @param SearchCriteriaInterface $searchCriteria
 * @return bool
 */
private function isSortedByPosition(SearchCriteriaInterface $searchCriteria): bool
{
    foreach ($searchCriteria->getSortOrders() as $sortOrder) {
        if ($sortOrder->getField() === 'position') {
            return true;
        }
    }
    return false;
}
Was this page helpful?
0 / 5 - 0 ratings