Search code examples
shopwareshopware6shopware6-app

How to add entity extension in Shopware 6 App?


I want to query the categories of the product in the product listing of a Shopware app, so that I can query the customFields of all categories. Is this even possible with an app?

I have already tried via a navigation-page-loaded. And when I override the box-standard.html.twig and access the product, I can't access the categories there.

For each product i want the categories extensions

enter image description here


Solution

  • As the categories association is not loaded for products in the listing you have to fetch the categories using an app script.

    As already noted, add the script to the navigation-page-loaded hook, i.e. in Resources/scripts/navigation-page-loaded/category-loader.twig:

    {% set products = [] %}
    
    {% if hook.page.cmsPage.type === 'product_list' %}
        {% foreach hook.page.cmsPage.sections as section %}
            {% foreach section.blocks as sectionBlock %}
                {% if sectionBlock.type !== 'product-listing' %}
                    {% continue %}
                {% endif %}
    
                {% foreach sectionBlock.slots as slot %}
                    {% if slot.type !== 'product-listing' %}
                        {% continue %}
                    {% endif %}
    
                    {% foreach slot.data.listing.entities as product %}
                        {% set products = products|merge([product]) %}
                    {% endforeach %}
                {% endforeach %}
            {% endforeach %}
        {% endforeach %}
    {% endif %}
    
    {% set categoryIds = products|reduce((carry, v) => carry|merge(v.categoryIds), []) %}
    {% if categoryIds %}
        {% set categories = services.repository.search('category', {'ids': categoryIds}) %}
    
        {% foreach products as product %}
            {% do product.addArrayExtension('myCategories', {
                'categories': categories.entities.getList(product.categoryIds),
            }) %}
        {% endforeach %}
    {% endif %}
    

    Where we first extract all the products, than load the categories of all products at once, and than assign the categories back to the products.

    Note that for reading the category entity you need the correct permission, i.e. in the manifest.xml add:

    <permissions>
        <read>category</read>
        <read>category_translation</read>
    </permissions>
    

    Now you should be able to access in the box-standard.html.twig template the categories using product.extensions.myCategories.categories.