Question

In the main view template for my grouped products, grouped.phtml, I have had no problems fetching the associated products and displaying some attributes in a loop.

I have done the same thing in a custom version of the attributes.phtml sub-template used to display attributes, and there, the code returns NULL.

<body>
    <attribute name="class" value="page-product-grouped"/>
    <referenceContainer name="product.info.form.content">
        <block class="Magento\GroupedProduct\Block\Product\View\Type\Grouped" name="product.info.grouped" before="product.info.addtocart" template="Magento_GroupedProduct::product/view/type/grouped.phtml"/>
        <container name="product.info.grouped.extra" after="product.info.grouped" before="product.info.grouped" as="product_type_data_extra" label="Product Extra Info"/>
    </referenceContainer>
    (...)
    <referenceBlock name="product.info.details">
        <block class="Magento\Catalog\Block\Product\View\Attributes" name="product.attributes" as="additional" template="Magento_GroupedProduct::product/view/type/grouped/attributes.phtml" group="detailed_info">
            <arguments>
                <argument translate="true" name="title" xsi:type="string">More Information</argument>
                <argument name="sort_order" xsi:type="string">27</argument>
            </arguments>
        </block>      
    </referenceBlock>              
</body>

I am assuming that the reason is because the second block is of class="Magento\Catalog\Block\Product\View\Attributes" but obviously if I change it to Magento\GroupedProduct\Block\Product\View\Type\Grouped then the attribute functionality disappears so I am not better off.

There has to be a way to "cross load" the Grouped functionality into the Attributes block (or vice versa) OR I must use something other than $block for the grouped loading code:

$_product = $block->getProduct();
$_associatedProducts = $block->getAssociatedProducts();

but what?

Was it helpful?

Solution

This is what I understood the question is.

I need the associated products in a template in which I have access to the product. How do I do that?

From the product object you can retrieve the type instance. And from the type instance you can retrieve the associated products.

$associatedProducts = $product->getTypeInstance()->getAssociatedProducts($product);

If your product is grouped, getTypeInstance() will return a Magento\GroupedProduct\Model\Product\Type\Grouped instance which implements getAssociatedProducts it also implements getAssociatedProductsCollection if you want to add some extra filters.

I hope this answers your question. If I did not get the question right, please put me on the right track.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top