Magento 2 – Product Collection Sort Order by Custom Attribute

magento-2.1magento-2.1.3magento2

I have a problem to list products collection by a custom attribute.

I created a product custom attribute of decimal type.
I made this attribute usable for sorting products ("used_for_sort_by").

At first sight the result is good: the new filter choice appears. But there is an issue: the values 'null' and '0.0000' are bigger than positive values.

So: when listing in ASC order: the products with the null or 0 value in this attribute are listed in last and when listing in DESC order they are listed in first, the opposite that it should be.

Any hint?

EDIT: this is how I created my product custom attribute, in UpgradeData.php

 if (version_compare($context->getVersion(), '1.5.0') < 0) {
        try {
            // Attribute to count sales qty
            $eavSetup = $this->eavSetupFactory->create(['setup' => $this->setup]);

            $eavSetup->addAttribute(
                Product::ENTITY,
                ExtendedProduct::SALES_COUNTER,
                [
                    'type' => 'decimal',
                    'label' => 'Quantity sold',
                    'input' => 'text',
                    'global' => ScopedAttributeInterface::SCOPE_WEBSITE,
                    'visible' => false,
                    'required' => true,
                    'user_defined' => false,
                    'default' => 0,
                    'searchable' => false,
                    'filterable' => false,
                    'comparable' => false,
                    'visible_on_front' => false,
                    'used_in_product_listing' => true,
                    'used_for_sort_by' => true,
                    'unique' => false,
                    'apply_to' => '',
                    'group' => 'General',
                    'system' => true
                ]
            );

Best Answer

OK. I asked the question to the Magento Partner Support: it is the normal behavior.

The behavior you are seeing is the designed behavior. For sorting and assigning priority Magento always places 0 as the first option, followed by 1. This means when a rule or product with a priority of 0 will be placed first.