Magento2: attributes of a product from a custom attribute group


December 15, 2016 at 13:55
Magento2

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.


Hinterlasse einen Kommentar:
Search