2

I created a custom drop down attribute in Magento2 from admin. I tried to collect all associated products by using filters. I am able to filter product collection based on text field attributes, for example

$productcollection = $this->_productCollection
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('sku', '24-MB01')
    ->load();

But when I try to filter using dropdown custom attribute value I'm getting an empty array

$productcollection = $this->_productCollection
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('tag', 'popular')
    ->load();

How am I supposed to filter product collection using a dropdown attribute. Can someone help with this?

1
  • 1
    thanks for your response. i'm looking drop down attribute product collection .Exp : attribute_code (tags) type->dropdown, drop down value (popular,new ......) i need collect all the popular products in the collection.
    – Suresh C
    Feb 7, 2017 at 8:51

2 Answers 2

5

For dropdown attribute, We can filter using dropdown option ID instead of Label.

So your code is like below.

$productcollection = $this->_productCollection
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('tag', 28)
    ->load();

Above 28 is the ID of the popular option of tag dropdown attribute.

enter image description here

2

I assume the 'Tag' is your attribute you created in the admin and the value 'Popular' is a option label associated with one of the option id with attribute 'Tag' not the value itself. The value might be an integer number internally used by magento.

As per the answer here : Loading a product collection by a specific attribute drop-down value , It is not possible to filter collection based on the option label, however you can filter the collection based on attribute option id, i.e. the integer value. You can get the option id for an option label, in your case 'popular' from the model.

You can use the code from the answer in the link I mentioned above. I hope it helps you.

PS: I did not add this answer in comment simply because I CAN NOT. I do not have enough reputation to comments. So, instead of down voting for posting an answer instead of comment, post requirement at meta stack exchange to give ability to comment with lower reputation.

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.