Magento2: Attribute eines Produkts aus einer bestimmten Attributgruppe

Um im Magento in einer phtml Datei alle Attribute eines Produkts, die zu einer bestimmten Gruppe (namens „customattributes“) gehören, habe ich mir einen Helper geschrieben, der folgendes macht:

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

Das liefert ein schönes Array mit allen Attributen und ihren Werten für das aktuelle Produkt zurück.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.