How to Retrieve Custom Attribute Set ID by Name

attribute-setmagento-2.1programmatically

I have created couple of custom Attribute Set and now I want to assign a group in those attribute sets programmatically, so is there any way to retrieve attribute set IDs based on name?

Best Answer

You can retrieve attribute set ID by using following code:

protected $_attributeSetCollection;

public function __construct(
     ...
     ,\Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $attributeSetCollection
)
    {
        ...
        $this->_attributeSetCollection = $attributeSetCollection;
    }


public function getAttrSetId($attrSetName)
    {
        $attributeSet = $this->_attributeSetCollection->create()->addFieldToSelect(
                    '*'
                    )->addFieldToFilter(
                            'attribute_set_name',
                            $attrSetName
                    );
        $attributeSetId = 0;
        foreach($attributeSet as $attr):
            $attributeSetId = $attr->getAttributeSetId();
        endforeach;
        return $attributeSetId;
    }

You can call getAttrSetId method by passing the attribute set name for which you want to retrieve attribute set ID. eg. $this->getAttrSetId("YourAttributeSetName");

Related Topic