2

Considering below I can display products with true value of my custom attribute in ascending order based on position. How can I have products with false right after these in ascending too?

if ($subject->getCurrentOrder() == 'CustomAttribute') {
            $collection ->addAttributeToFilter('myCustomAtt',1)->setOrder('position', 'asc');
            $collection->load();
        }

Is there any way to append $collection ->addAttributeToFilter('myCustomAtt',0)->setOrder('position', 'asc'); at the end of the $collection?

3
  • i don't get you want to double sort the collection based on position and your custom attribute value? Mar 7, 2018 at 7:37
  • it's like displaying all products with true value then all with fasle on my custom attribute, in ascending.
    – Zinat
    Mar 7, 2018 at 8:59
  • I added the answer hope it will helpful Mar 7, 2018 at 9:27

3 Answers 3

2

You can sort it by give values

if ($subject->getCurrentOrder() == 'CustomAttribute') {
     $values=array(1);
                $collection->setOrder('position', 'asc');
$collection->getSelect()->order(new \Zend_Db_Expr('FIELD(myCustomAtt,' . implode(',', $values).')'));
                $collection->load();
            }

Check for detail

8
  • after more testing, I realized it does not list all products, it just displays neq' => '1' collection :(
    – Zinat
    Mar 7, 2018 at 12:36
  • @Zinat just remove the filter part. update the code check it Mar 7, 2018 at 12:40
  • now I have exactly your code, but I don't get getSelect()->order(new \Zend_Db_Expr('FIELD(myCustomAtt,' . implode(',', $values).')')); at the end of the collection
    – Zinat
    Mar 7, 2018 at 12:43
  • @Zinat you want to sort the current attribute value first. this is code doing Mar 7, 2018 at 12:48
  • let's forget $collection->setOrder('position', 'asc') for now ... First we display collection that has myCustomAtt as true and then collection that has myCustomAtt as false ... and thanks for following up
    – Zinat
    Mar 7, 2018 at 12:52
0

In this case, you should use sorting instead of filtering.

The following code will sort by myCustomAtt first, then by position.

if ($subject->getCurrentOrder() == 'CustomAttribute') {    $collection->addAttributeToSort('myCustomAtt','DESC')->addAttributeToSort('position','ASC');
    $collection->load();
}
2
  • Exception #0 (Zend_Db_Select_Exception): You cannot define a correlation name 'myCustomAtt_t' more than once, what does it mean?
    – Zinat
    Mar 7, 2018 at 9:01
  • You cannot use addAttributeToSort on 'myCustomAtt' twice Mar 7, 2018 at 9:17
0

It will work for you.

    $collection->addAttributeToFilter('myCustomAtt', array('eq' => array(1,0)))->setOrder('position', 'asc');
    $collection->load();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.