Magento 2 Checkout – How to Get Product Attribute Options on Checkout Cart

attribute-optionsattributescheckout-pagemagento2

How I can get the configurable products attribute options in front end checkout cart page? I have tried with the below answer but can't get any success.

Magento 2 – How to get attribute options value of eav entity?

When I have print the echo "<pre>"; print_r($block->getOptionList()); die;, I am getting the below array result with the label and value but not getting the color code to show as per my custom design.

Array
(
    [0] => Array
        (
            [label] => Color
            [value] => Green
        )

    [1] => Array
        (
            [label] => Size
            [value] => S
        )

)

Also, I have go through the admin settings like below:

Stores > Configutation > Sales > Checkout > Shopping Cart > Configurable Product Image set as Product Thumbnail Itself

It's also not working in the magento 2.

Please see the attached screenshot what I want:
enter image description here

Display this color code value in the frontend like the below image:
enter image description here

Please suggest how I can get the color code? Thanks!!!

Best Answer

  1. Create a module

  2. Override the configurable model in

VENDOR/MODULENAME/Model/Product/Type/Configurable.php

namespace VENDOR\MODULENAME\Model\Product\Type;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableProduct;

class Configurable extends \Magento\ConfigurableProduct\Model\Product\Type\Configurable
{   
    public function getUsedConfigurableProductAttributes($product)
    {       
        if (!$product->hasData($this->usedProductAttributes)) {
            $usedProductAttributes = [];
            $usedAttributes = [];
            foreach ($this->getConfigurableAttributes($product) as $attribute) {
                if ($attribute->getProductAttribute() !== null) {
                    $id = $attribute->getProductAttribute()->getId();
                    $usedProductAttributes[$id] = $attribute->getProductAttribute();
                    $usedAttributes[$id] = $attribute;
                }
            }
            $product->setData($this->_usedAttributes, $usedAttributes);
            $product->setData($this->usedProductAttributes, $usedProductAttributes);
        }
        return $product->getData($this->_usedAttributes);
    } 
}
  1. Override the Getoptions block using plugin

    namespace VENDOR\MODULENAME\Plugin\Product;
    use Magento\Swatches\Helper\Data as SwatchData;
    use Magento\Swatches\Helper\Media;
    use VENDOR\MODULENAME\Model\Product\Type\Configurable as ConfigModel;
    
    class Options
    {
        protected $swatchHelper;    
        protected $swatchMediaHelper;    
        protected $configModel;
    
        public function __construct(
            SwatchData $swatchHelper,
            Media $swatchMediaHelper,
            ConfigModel $configModel
        )
        {
            $this->swatchHelper = $swatchHelper;
            $this->swatchMediaHelper = $swatchMediaHelper;
            $this->configModel = $configModel;        
        }
    
        public function aroundGetOptions(
            \Magento\Catalog\Helper\Product\Configuration $subject,
            $proceed,
            \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface $item
        ) {     
            $product = $item->getProduct();
            $typeId = $product->getTypeId();
    
            if ($typeId == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
                if($attributesOption = $product->getCustomOption('attributes')) {
                    $data = unserialize($attributesOption->getValue());  
    
                    $usedAttributes = $this->configModel->getUsedConfigurableProductAttributes($product);
                    $mediaUrl = $this->swatchMediaHelper->getSwatchMediaUrl();
    
                    foreach ($data as $attributeId => $attributeValue) {
                        if (isset($usedAttributes[$attributeId])) {
                            /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
                            $attribute = $usedAttributes[$attributeId]->getProductAttribute();
                            $label = $attribute->getStoreLabel();
                            $value = $attribute;
                            if ($value->getSourceModel()) {
                                $value = $value->getSource()->getOptionText($attributeValue);
                            } else {
                                $value = '';
                            }
    
                            $swatchesData = $this->swatchHelper->getSwatchesByOptionsId(array($attributeValue));
                            $swatchValue = $swatchesData[$attributeValue]['value'];
                            $visualSwatch = $this->swatchHelper->isVisualSwatch($attribute);
                            $swatch_value_formatted = '';
    
                            if($visualSwatch) {
                                if ($swatchValue[0] == '#') {
                                    $swatch_value_formatted = 'background: '.$swatchValue;
                                } elseif ($swatchValue[0] == '/') {
                                    $swatch_value_formatted = 'background: url('.$mediaUrl.$swatchValue.'); background-size: cover;';
                                }
                            }
    
                            $attributes[] = ['label' => $label, 'value' => $value, 'swatch_value' =>  $swatchValue, 'option_id' =>  $swatchesData[$attributeValue]['option_id'] , 'visual_swatch' => $visualSwatch , 'swatch_value_formatted' => $swatch_value_formatted  ];      
                        }
                    }
                }            
                return $attributes + $proceed($item);
            }        
            return $proceed($item);
        }
    }
    
  2. Define the plugin and overriding model in di.xml


<preference for="Magento\ConfigurableProduct\Model\Product\Type\Configurable" type="VENDOR\MODULENAME\Model\Product\Type\Configurable"/>
<type name="Magento\Catalog\Helper\Product\Configuration">
<plugin name="My_product_options" type="\VENDOR\MODULENAME\Plugin\Product\Options" sortOrder="1"/>
</type>
  1. In the checkout cart template you can use the following to find out the swatch is visual or not. The following values also available in the template file swatch_value, visual_swatch, swatch_value_formatted

<?php if (isset($_option['visual_swatch']) && $_option['visual_swatch']) { ?>
        <?php echo '<div class="swatch-option" style="'.$_option['swatch_value_formatted'].'"></div>'; ?>
    <?php } ?> 
Related Topic