Question

If the configurable product has size, I want to add a size guide for it. But how can I check that product have the size or not?

configurable product

Was it helpful?

Solution 4

Thank you all, you guys. I have checked it by this code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');

$data = $product->getTypeInstance()->getConfigurableOptions($product);

$show_size = false;
foreach ($data as $key => $value) {
     if($value['0']['attribute_code'] == 'size')
     {
         $show_size = true;
         break;
     }
}

Hope this helps someone!

OTHER TIPS

Try this

  //check product is configurable 

  if ($product -> getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE){
      //if product is configurable

      $product -> hasData('size');
          //OR
      $product  > hasSize();

  }

Hope this help you, Thanks

Option 1:

$size = $_product->getResource()->getAttribute('size')->getFrontend()->getValue($_product);

Option 2

$size = $_product->getSize();

Then you just need to check it exists and output your block

if($size) {
      $this->getLayout()
          ->createBlock('Magento\Cms\Block\Block')
          ->setBlockId('size_guide')
          ->toHtml();
}
 use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

 class yourclass{
  const CONFIGURABLE = "configurable";

   protected $_productCollection;

   public function __construct(

    CollectionFactory $collectionFactory,
    ) {
      $this->_productCollection = $collectionFactory;
    }

    public function yourfunction
    {
      $products = $this->_productCollection->create();
      foreach($products as $product){
       if ($product->getTypeId() == self::CONFIGURABLE ) {
       if($product->getOptions()){
         // if options are their
         // do your rest of work
      }else{
       //if no options are their
        }
       }
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top