skip to Main Content

In a Magento 2.3.3 store I am trying to ouput the values of a multiselect custom attribute on a category page, but not having any luck.
I have set the attribute to be used in product listing and tried to output it on catalog/product/listing.phtml template page in my custom theme.
I am using the using the following code:
<?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('custom_attribute')->getFrontend()->getValue($_product); ?>
This is working for dropdown attributes but not multi select attributes.
Kind of stuck on this…

2

Answers


  1. You can use the below code to get MultiSelect Attribute value

    create block in “catalog_product_view.xml”

    <referenceBlock name="product.info.main">
        <block class="MagentoCatalogBlockProductView" name="attribue.name" template="Magento_Catalog::product/view/attribute_name.phtml" after="-"  /> 
    </referenceBlock>
    

    create “phtml” file under “Magento_Catalog::product/view/attribute_name.phtml”

    <?php $product = $block->getProduct(); ?> 
    <div>
      <?php 
        $data = explode(',',$product->getData('attribute_code'));
        foreach($data as $value):            
      ?>
      <?php 
        $attr = $product->getResource()->getAttribute('attribute_code');
        if ($attr->usesSource()): 
      ?>
            <?php 
                $option_value = $attr->getSource()->getOptionText($value);
            ?>
            <p><?php echo $option_value; ?></p>
        <?php endif;?>
     <?php endforeach;?>
    </div>
    
    Login or Signup to reply.
  2. Here is an example of a code that returns "Multiselect Attribute Values". The attribute belongs to product entity. As it isn’t a good idea to get ProductResource model from ProductModel and taking into account that probably you need to get it inside some template, just create a ViewModel and use this example there.

    use MagentoCatalogModelResourceModelProduct as ProductResource;
    ...
    public function __construct(
        ...
        ProductResource           $productResource
    )
    {
        ...
        $this->productResource = $productResource;
    }
    
    public function prepareProductAttributeOptions($product, $attributeCode)
    {
        $result = [];
        $data = $product->getData($attributeCode);
        $optionsIds = [];
        if ($data) {
            $optionsIds = explode(',', $data);
        }
    
        foreach ($optionsIds as $optionId) {
            $attr = $this->productResource->getAttribute($attributeCode);
            if ($attr->usesSource()) {
                $option_value = $attr->getSource()->getOptionText($optionId);
                $result[] = $option_value;
            }
        }
    
        return implode(',', $result);
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search