3

I have a list of products (books) with a custom eav multiple select attribute named 'authors' in magento 2. This attribute is 'visible_on_front' and also 'used_for_sort_by'.

I am trying to use that multiselect attribute for sorting my products in frontend by the attributes option value (specific: the first option value if more than one option is assigned).

Therefore I extended the Magento\Catalog\Block\Product\ProductList\Toolbar and manipulated the setCollection($collection) method like so:

public function setCollection($collection)
{
    $this->_collection = $collection;

    $this->_collection->setCurPage($this->getCurrentPage());

    // we need to set pagination only if passed value integer and more that 0
    $limit = (int)$this->getLimit();
    if ($limit) {
        $this->_collection->setPageSize($limit);
    }
    if ($this->getCurrentOrder()) {
        if ($this->getCurrentOrder() == 'position') {
            $this->_collection->addAttributeToSort(
                $this->getCurrentOrder(),
                $this->getCurrentDirection()
            );
        } else {

            // START CUSTOM PART -> the user selected 'Sort by author'
            // where
            // $this->getCurrentOrder() resolves in 'authors' and
            // $this->getCurrentDirection() resolves in 'asc' or 'desc'
            $this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
            // END CUSTOM PART

        }
    }
    return $this;
}

I expected to get a productlist in frontend, that is sorted by the authors name (= custom attribute option value). And in my first impression it seemed to work fine. But after checking the frontend, I noticed, that NOT all products were sorted correctly. After further investigation I found out, that it looks like my product list is getting sorted by the custom attributes option key instead of the options value.

Example: 3 simple products with author names (attribute option id in brackets)

- product1 - Obama, Michelle (7)
- product2 - Bannour, Karim-Patrick(6); Grabs, Anne(1); Vogl, Elisabeth(2)
- product3 - Bloom, Cameron(8)

Expected ordering:

product2 > product3 > product1.

Actual ordering:

product2 > product1 > product3

This is very confusing, due to the fact that magento allows us to make multi-selection eav's 'used_for_sort_by'.

Is it possible to order my collection to achieve a sorting based on the authors name.

If not, how could I achieve this.

Your Answer

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

Browse other questions tagged or ask your own question.