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?

sv3n
11.7k7 gold badges44 silver badges75 bronze badges
asked Feb 7, 2017 at 6:57
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. Commented 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

sv3n
11.7k7 gold badges44 silver badges75 bronze badges
answered Feb 6, 2018 at 3:08
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.

answered Oct 28, 2017 at 0:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.