Magento2: attributes of a product from a custom attribute group

To get all the attributes from a custom group (named “customattributes”), I created a helper that looks like this:

class Product extends \Magento\Framework\App\Helper\AbstractHelper
{
    const CUSTOMATTRIBUTE_GROUP_NAME = 'customattributes';

    public $groupCollectionFactory;

    public function __construct(
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory $groupCollectionFactory
    ){
        $this->groupCollectionFactory = $groupCollectionFactory;
    }

    public function getAttributesForProduct($_product){
        $groupCollection = $this->groupCollectionFactory->create();
        $groupCollection->addFieldToFilter('attribute_group_name',self::CUSTOMATTRIBUTE_GROUP_NAME);
        $groupCollection->addFieldToFilter('attribute_set_id', $_product->getAttributeSetId());
        $group = $groupCollection->getFirstItem();

        $data = array();
        $c = 0;
        $productAttributes= $_product->getAttributes();
        foreach ($productAttributes as $attribute) {
            if ($attribute->isInGroup($_product->getAttributeSetId(), $group->getAttributeGroupId())) {
                if ($attribute->getFrontend()->getValue($_product)) {
                    $data[$c]['attribute'] = $attribute->getFrontendLabel();
                    $data[$c]['value'] = $attribute->getFrontend()->getValue($_product);
                    $c++;
                }
            }
        }
        return $data;
    }
}

This returns an array with all the attributes and their values.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.