Get all assigned attributes from the attribute set id in Magento 2 useful to know the list of available attributes for the given attribute set.
Let’s take an example, We want to fetch all the assigned attributes from the Default Attribute set in Magento 2.
The Default Attribute set id is 4 in Native Magento.
We required to interface to fetch all the attribute is, Magento\Catalog\Api\ProductAttributeManagementInterface
Base Definition of the method,
public function getAttributes($attributeSetId);
$attributeSetId is the attribute set id we want to explore related attributes.
<?php namespace Jesadiya\GetAttributes\Model; use Magento\Framework\Exception\LocalizedException; use Magento\Catalog\Api\Data\ProductAttributeInterface; use Magento\Catalog\Api\ProductAttributeManagementInterface; class GetAttributes { /** * @var ProductAttributeManagementInterface */ private $productAttributeManagement; public function __construct( ProductAttributeManagementInterface $productAttributeManagement ) { $this->productAttributeManagement = $productAttributeManagement; } /** * Get Product Attributes from the attribute set. * * @return ProductAttributeInterface[] */ public function getAttributeListBySetId() { $attributeSetId = 4; // Default Attribute set try { $getAttributes = $this->productAttributeManagement ->getAttributes($attributeSetId); } catch (NoSuchEntityException $exception) { throw new NoSuchEntityException(__($exception->getMessage())); } return $getAttributes; } }
We need to call the method and iterate over a loop to fetch all the attributes from the attribute set.
$getAttributes = $this->getAttributeListBySetId(); foreach ($getAttribute as $attribute){ var_dump($attribute->debug()); }
Output:
On Success, \Magento\Catalog\Api\Data\ProductAttributeInterface[]
On Error, No such entity with id.