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 ?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI 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 ?
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;
}
You can use the below code for filtering by group id:
$groupId = 1;
$this>_objectManager>create('Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection')->setAttributeGroupFilter($groupId);
In my opinion the easiest way :
use Magento\Eav\Api\AttributeManagementInterface;
public function __construct(
AttributeManagementInterface $attributeManagement,
.....
)
{
$this->_attributeManagement = $attributeManagement;
.....
}
/**
* @return \Magento\Eav\Api\Data\AttributeInterface[]
*/
public function getAttributesetAttributes($attributesetid){
$attributes = $this->_attributeManagement->getAttributes(ProductAttributeInterface::ENTITY_TYPE_CODE,$attributesetid);
return $attributes;
}