1

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 ?

2
  • Are you looking for list of attribute of Attribute set? Commented Jan 4, 2017 at 7:04
  • 1
    List of attribute in a attribute group. Not based on attribute set.
    – BornCoder
    Commented Jan 4, 2017 at 7:10

3 Answers 3

1

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;
}
1
  • 1
    Thanks Marius , It's really helpful and its works for me.
    – BornCoder
    Commented Jan 4, 2017 at 7:52
0

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);
1
  • I tried this but its not working
    – BornCoder
    Commented Jan 4, 2017 at 12:06
0

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;
    }

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.