2

In constructor inject dependency

protected $productAttInterface;
\Magento\Catalog\Api\ProductAttributeManagementInterface $productAttInterface

$this->productAttInterface=$productAttInterface;

and get all attributes of a specific attribute set

$attributeSetId=16; //This is Attribute Set Id

return $this->productAttInterface->getAttributes($attributeSetId);

Now i want to get all attributes of a specific group . I make a group and add 5 attributes. I want to just get these 5 attributes not all. Can anyone guide me how get attributes of specific group by giving group_name or group_id ?

0

1 Answer 1

1

Try to use this below code. It may be helpful for you :

protected $attributeGroupCollection;
protected $productAttributeCollection;

public function __construct(
    ..........
    \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory $attributeGroupCollection,
    \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $productAttributeCollection
    ..........
)
{
    ..........
    $this->attributeGroupCollection = $attributeGroupCollection;
    $this->productAttributeCollection = $productAttributeCollection;
    ..........
}

public function yourFunction(){
    $attributeSetId = 4;
    // \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory
    $groupCollection = $this->attributeGroupCollection->create()
        ->setAttributeSetFilter($attributeSetId)
        ->load(); // product attribute group collection
    $attributeCollection = [];
    foreach ($groupCollection as $group) {
        // \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory
        $groupAttributesCollection = $this->productAttributeCollection->create()
            ->setAttributeGroupFilter($group->getId())
            ->addVisibleFilter()
            ->load(); // product attribute collection

        foreach ($groupAttributesCollection->getItems() as $attribute) {
            if($attribute->getAttributeGroupId() == 14){
                $attributeCollection[] = $attribute->getData();
            }
        }
    }
    echo "<pre>";
    print_r($attributeCollection);
    exit;
}

Your Answer

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

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