Search code examples
shopware6shopware6-app

Add custom fields to the taxRule entity


How is it possible to add custom data to any configured tax rule with different values? Sadly there is no customField property available at the taxRule entity. Its possible to add customFields to the tax entity, but then this only can have one value for all configured countries. Maybe there is another approch to solve this?


Solution

  • What you're trying to do and how it could be achieved is depending on two things:

    • Are you developing a plugin or an app?
      • Does the user have to set the custom fields or would it be ok to set them using the API only?

    With a plugin

    If you're developing a plugin you could extend the TaxRuleDefinition with an association to a custom entity with the fields of the custom entity essentially being your custom fields.

    If you're ok with simply setting the fields of your custom entity via the API, you're good to go. Given your custom entity is called tax_rule_custom_field:

    // POST|PATCH /api/tax-rule-custom-fields
    {
      "id": "...",
      "taxRuleId": "...",
      "customField": "...",
      "anotherCustomField": true
    }
    

    If you want the user to set these fields from within the UI of the administration, you'll have to extend the administration and register custom components or override existing components to inject the various fields where you want them to show up and make them persist when the user saves changes.

    I created an example plugin that adds additional fields to the customer in the same manner and injects input fields for them in the administration. The same basic principle could be used for tax rules.

    With an app

    If you're developing an app you may also add a custom entity to contain your fields. However, as far as I know, you can't yet extend existing entities yet, like you can with a plugin, to add an association to the TaxRuleDefinition. So you'll have to resolve to loading and persisting the custom entity manually whenever needed, e.g. by using app scripts.

    Furthermore you can't extend the administration directly as you can with plugins. You'll have to add a custom module, with the UI and logic for loading and persisting the fields of your custom entity being hosted on your app server entirely. That's where you may use the API as explained above, in the part about plugins, to persist and load data of your custom entity.