1

I have a product object of a simple product which belongs to a configurable. I'm trying to get the attributes of the configurable which led to the simple I have. Since each simple of a configurable is the result of selecting options of that configurable, that should be possible.

I have the full simple product option and can easily get the Option value and Label of the attribute but only if I know the name of the attribute. Since the attribute is dynamic and can change I won't hardcode it.

There's a similar question for Magento 1 but that won't work for Magento 2.

How do I get the configurable options that led to the simple I have available?

1 Answer 1

1

I ended up resolving the parent product and mapping the configurable attributes from the parent to the ones the simple product has:

class ConfigurableAttributes implements ArgumentInterface
{
    private Configurable $configurable;
    private ProductRepository $productRepo;

    public function __construct(
        Configurable $configurable,
        ProductRepository $productRepo
    ) {
        $this->configurable = $configurable;
        $this->productRepo = $productRepo;
    }

    public function getConfigurableAttributes(Product $product): array
    {
        $parentId = $this->configurable->getParentIdsByChild($product->getId());

        if (count($parentId) === 0) {
            return [];
        }

        $parent = $this->productRepo->getById($parentId[0]);

        $attributes = $this->configurable->getConfigurableAttributes($parent);

        $resolvedAttributes = [];
        foreach($attributes as $attribute) {
            $attributeCode = $attribute->getProductAttribute()->getAttributeCode();
            $resolvedAttributes[$attributeCode] = [
                'label' => $attribute->getLabel(),
                'value' => $product->getAttributeText($attributeCode),
            ];
        }

        return $resolvedAttributes;
    }
}

This works but I feel like it adds too much unnecessary overhead because now I need to load the full product every time I want to get the configurable options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.