13

How can we retrieve the attribute set name for a product. I want to use it on product detail and listing page.

1 Answer 1

22

We can use \Magento\Eav\Api\AttributeSetRepositoryInterface to get attribute set name.

Detail Page

We need to override the \Magento\Catalog\Block\Product\View block. Inject this class on the constructor

/** @var \Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet **/
protected $attributeSet;

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


//Build method to get attribute set
public function getAttributeSetName() {

    $product = $this->getProduct();
    $attributeSetRepository = $this->attributeSet->get($product->getAttributeSetId());
    return $attributeSetRepository->getAttributeSetName();
}

Now, we can call in product detail page: $block->getAttributeSetName();

Listing page

We need to override \Magento\Catalog\Block\Product\ListProduct block

/** @var \Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet **/
protected $attributeSet;

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

public function getAttributeSetName($product) {

    $attributeSetRepository = $this->attributeSet->get($product->getAttributeSetId());
    return $attributeSetRepository->getAttributeSetName();
}

We can call $block->getAttributeSetName($_product).

9
  • $attributeSet and $product are undefined variables, I am very new to magento2 and I am not able to understand what exactly I need to write Sep 24, 2016 at 4:58
  • You can see my updated answer. Enough for you? Sep 24, 2016 at 5:34
  • I'm trying to implement it in product list block, but it is not working as exact, making some modifications Sep 24, 2016 at 5:36
  • I'm getting error object dom should be created Sep 24, 2016 at 5:37
  • You can update your answer with current issue when following my answer. Sep 24, 2016 at 5:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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