Magento – Magento 2 Use same Product attribute with different values for different categories

attributescategorymagento2product

I've created product drop-down attribute 'Types' for my project. But I want different values of that attribute for different category sections. For example: Let's say a category can be of type a) Fruits or b) Vegetables So for the category Fruits only options/values like Mango, Banana etc. should be visible and not the ones associated with Vegetables.

How to achieve this?

Best Answer

You could override the \Magento\Catalog\Block\Product\View\Attributes block and add a function to get the attribute set name:

Add something like this into overridden block:

public function __construct(
...
Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet,
...) {
...
$this->attributeSet = $attributeSet
....
}

function getAttributeSet($_product) {
    return $this->attributeSet->get($_product->getAttributeSetId())->getAttributeSetName();
}

Then from template you can grab a attribute set name and have more control over what attributes are shown for each product type:

$attributeSetName = $block->getAttributeSet($_product);

<?php if ($attributeSetName == "Fruit"): ?>
    <tr>
                        <th class="col label" scope="row"><?php echo $_product->getResource()->getAttribute('attribute1')->getStoreLabel(); ?></th>
                        <td class="col data">
                            <?php echo $_product->getAttributeText('attribute1'); ?></a>
                        </td>
                    </tr>   
<?php endif; ?>
<?php if ($attributeSetName == "Vegetable"): ?>
    <tr>
                        <th class="col label" scope="row"><?php echo $_product->getResource()->getAttribute('attribute2')->getStoreLabel(); ?></th>
                        <td class="col data">
                            <?php echo $_product->getAttributeText('attribute2'); ?></a>
                        </td>
                    </tr>   
<?php endif; ?>

File Location: Vendor/Theme/Magento_Catalog/templates/product/view/attributes.phtml

This will replace the grid within the product tabs.

Related Topic