Search code examples
shopware6shopware6-app

Does equalsAny filter work on JSON field of custom entity?


I'm using a custom entity (Blog) in my app, it has a field JSON format that contains list of product ID.

<?xml version="1.0" encoding="utf-8" ?>
<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/platform/trunk/src/Core/System/CustomEntity/Xml/entity-1.0.xsd">
    <entity name="custom_entity_blog">
        <fields>
            <!--...-->
            <bool name="status" store-api-aware="true"/>
            <json name="product_ids" store-api-aware="true" />
            <!--...-->
        </fields>
    </entity>
</entities>

I have tried to find custom entity by Status field and it works

{% set criteria = {
    'filter': [
        {
            "field": "status",
            "type": "equals",
            "value": 1
        }
    ]
} %}
{% set blog = repoService.search('custom_entity_blog', criteria).first %}

but find custom entity by JSON field it return null

{% set criteria = {
    'filter': [
        {
            "field": "productIds",
            "type": "equalsAny",
            "value": [hook.page.product.id]
        }
    ]
} %}
{% set blog = repoService.search('custom_entity_blog', criteria).first %}

Anyone has the same problem or maybe I am doing wrong?


Solution

  • You're defining a generic json field which may not contain a one-dimensional array, hence why the EqualsAny filter is incompatible with that field type.

    There is the ListField which is a confined json field that will only allow a list of values. That field would be compatible with the filter.

    Unfortunately the schema for custom entities in apps currently does not allow the definition of list fields. If you can't rely on a regular plugin and it has to be an app, you'll have to resolve this programmatically as of today. You could also create an issue ticket asking for a future inclusion of the list field for custom entities in apps. If you have the time you could also try your hand on creating a pull request and adding the missing field type yourself.

    Alternative

    Since you are trying to filter for an ID, it might be feasible to use a ContainsFilter instead, since the chance of mismatches is basically non-existing with IDs in particular.

    {
        "field": "productIds",
        "type": "contains",
        "value": hook.page.product.id
    }
    

    While not exactly a clean approach, this should work with json type fields and in your particular case.