ALTCHA: Storefront Integration
ALTCHA spam protection for Sylius - placing the widget in custom forms via Twig function or hook, behaviour with theme overrides and the hook-prefix pitfall
ALTCHA: Storefront Integration
Live Demo: Try this and other plugins live — no installation, no risk: demo.markus-michalski.net
Built-in forms get their widget from Twig hooks this plugin registers; nothing extra is needed for them.
For any other form, place the widget once in its template - two equivalent ways:
With the plugin as a dependency
Call the Twig function directly. It renders nothing unless that target is protected in the current channel, so it is safe to leave in permanently:
{{ mmd_altcha_widget('<target code>') }}
Without depending on the plugin
For example in a template shipped by another plugin: render a hook instead. An undefined hook renders nothing, so this stays harmless wherever this plugin is absent:
{% hook 'mmd_altcha.widget.support_form' %}
{% hook 'mmd_altcha.widget.newsletter' %}
{% hook 'mmd_altcha.widget' with { target: 'custom_order_form' } %}
The target code is support_form or newsletter for the two sibling plugins, and the code you chose in the admin for a custom form (prefix custom_). Tick the target in the channel settings only once the widget is in place (see Configuration).
Whether the two sibling plugins already render the widget depends on their version. Before ticking
support_formornewsletter, check that their templates contain{% hook 'mmd_altcha.widget.support_form' %}or{% hook 'mmd_altcha.widget.newsletter' %}.
When a theme replaces a form template
If your theme replaces a built-in form template (for example Sylius' own
sylius_shop.contact.contact_request.content.formhook) and drops the widget, every submission of that form is rejected, because the built-in targets are ticked from the start. Either untick the target or put the widget back.
The Twig function is the simplest way. The target codes of the built-in forms are contact, registration, login and password_reset_request:
{{ mmd_altcha_widget('contact') }}
Hook from a hook-rendered template: _prefixes: []
When you call a hook from inside a template that is itself rendered by a hook, pass _prefixes: []. Sylius otherwise prefixes the inner hook's name with the outer one (here sylius_shop.contact.contact_request.content.form.mmd_altcha.widget). That hook does not exist, so nothing is rendered and there is no error:
{% hook 'mmd_altcha.widget' with { target: 'contact', _prefixes: [] } %}
The same applies to mmd_altcha.widget.support_form and mmd_altcha.widget.newsletter when they are called from a template rendered by a hook.
After every change, open the form in the shop and check that the widget actually appears. If something goes wrong, see Troubleshooting.