10

I made product attribute and assign it on of attribute set so that it will show in the admin product detail page. Based on this product attribute I sort the product collection on category page.

The problem is, I set the Catalog Input Type for Store Owner to Text field. I will have to set the numeric value against each product in order to sort the product collection based on this attribute. It works fine from 1-9 but when I increase the count more than 9 like 10, 11 etc it destroy the sorting. It may be because field type is not number type

Any help, experience and knowledge sharing would be appreciated.

3

Please try following way using custom plugin, so please add plugin code in your custom extension as below

/Vendor/Module/etc/frontend/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\Catalog\Block\Product\ProductList\Toolbar">
        <plugin name="vendormodule_catalog_block_product_listproduct_toolbar" type="Vendor\Module\Plugin\Catalog\Block\Product\ProductList\Toolbar"/>
    </type>
</config>

/Vendor/Module/Plugin/Catalog/Block/Product/ProductList/Toolbar.php

<?php

namespace Vendor\Module\Plugin\Catalog\Block\Product\ProductList;

class Toolbar
{
    /**
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry;

    public function __construct(\Magento\Framework\Registry $coreRegistry)
    {
        $this->_coreRegistry = $coreRegistry;
    }

    /**
     * @param \Magento\Catalog\Block\Product\ProductList\Toolbar $toolbar
     * @param \Magento\Framework\Data\Collection $collection
     * @return array
     */
    public function beforeSetCollection(
        \Magento\Catalog\Block\Product\ProductList\Toolbar $toolbar,
        $collection
    ){
        $collection->getSelect()->group('e.entity_id')->order('{YOUR CUSTOM ATTRIBUTE CODE} ASC');
        $collection->getSize();

        return [$collection];
    }
}

Please try and let me know if you get any issue.

  • Bro I use the same for sorting. It works fine when I enter the value from 1-9 in my custom product attribute but when I increase the value from 9 like 10, 11. It will destroy the sorting like I said in my question. Anyways thanks for answering. For your effort. +1 – Muhammad Hasham Apr 24 at 6:25
  • So try with change in your database attribute type to int – Aasim Goriya Apr 24 at 6:30
  • During product attribute creation from admin, is there anyway to set product attribute type to int? There is nothing in Catalog Input Type for Store Owner like number or etc – Muhammad Hasham Apr 24 at 6:35

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.