0

The following piece of code:

$yesNo = $product->getData('upcoming');
if($yesNo = "Yes") {
    $labels['upcoming'] = 'Upcoming';
}

Is supposed to add a label on products for which the yes/no attribute has been set on 'Yes', but now all products get the label (even those for which the value of the attribute is 'No')

How to correct for this?

5
  • You need to use == instead of = in your if condition. Also try using value 1 or 0 to check Yes and No respectively. Oct 31 '18 at 11:46
  • == "Yes", == 'Yes', == "yes", =='yes', == '1' and == "1" do not work Oct 31 '18 at 11:51
  • Have you checked the value for your variable $yesNo by using var_dump($yesNo)? Make sure you are getting the value in your variable before using it in your condition. Oct 31 '18 at 12:03
  • May be re-indexing and clearing your cache could help. Oct 31 '18 at 13:09
  • have you tried echo $product->getUpcoming(); ?
    – Pawan
    Nov 1 '18 at 3:07
2

Try using below code to get value for your attribute

$yesNo = $product->getResource()->getAttribute('upcoming')->getFrontend()->getValue($product);

Then you can check the value by using var_dump($yesNo) for your product attribute.

6
  • var_dump returns NO for all products, irrespective of the value of the yes/no attribute: object(Magento\Framework\Phrase)#3246 (2) { ["text":"Magento\Framework\Phrase":private]=> string(2) "No" ["arguments":"Magento\Framework\Phrase":private]=> array(0) { } } Oct 31 '18 at 12:31
  • If you are using this on product list page, just try setting the value for the first product in the list to 'Yes'. It may happen that the product object you are using is being cached and gets value from the same object every time. Oct 31 '18 at 12:40
  • I checked already, but still var_dump returns NO for all products (even for those for which the attribute is Yes) 🤔 the attribute code is ok; anything else to bear in mind? Oct 31 '18 at 12:52
  • I cant think of anything else which can cause this issue except if the scope of your attribute. If it is store_view, then you may require to check the attribute value for the particular store in admin panel. Oct 31 '18 at 12:56
  • 1
    Jaimin, the issue was related to the configuration of the attribute :) i only have an extra question: that check works for simple products, but what about configurable ones? Should all childs and the parent have the value ‘Yes’ so that a similar check can also work for configurable products? Oct 31 '18 at 19:47

Your Answer

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

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