Magento2 – How to Get All Product Attributes of an Attribute Group in Default Attribute Set

attributesmagento2module

I want to get the collection of all product attributes of an attribute group in the Default attribute set in Magento 2.

Is there any filter available like group_id or group name or something else ?

Best Answer

you can add this to your class:

protected $attributeRepository;
protected $searchCriteriaBuilder;
protected $sortOrderBuilder;

public function __construct(
    ....
    \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
    \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository,
    \Magento\Framework\Api\SortOrderBuilder $sortOrderBuilder,
   ....
)
{
    ....
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->attributeRepository = $attributeRepository;
    $this->sortOrderBuilder = $sortOrderBuilder;
    ....
}

Now you added the dependencies. You need a method to retrieve the attributes based on the attribute group id.

public function getAttributes($groupId)
{
    $sortOrder = $this->sortOrderBuilder
            ->setField('sort_order')
            ->setAscendingDirection()
            ->create();
    $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter(\Magento\Eav\Api\Data\AttributeGroupInterface::GROUP_ID, $groupId)
            ->addFilter(\Magento\Catalog\Api\Data\ProductAttributeInterface::IS_VISIBLE, 1) //if you want only visible attributes
            ->addSortOrder($sortOrder)
            ->create();
    $groupAttributes = $this->attributeRepository->getList($searchCriteria)->getItems();
    return $groupAttributes;
}
Related Topic