0

I'm trying to add a captcha to a custom form that I created in a CMS page in Magento. The captcha is working correctly on the default Contact Us page, but it's not refreshing every time on my custom form.

Here's how I'm currently calling the captcha block in my CMS page's theme PHTML file:

<?php 
/** 
 * @var \Magento\Captcha\Block\Captcha $captchaBlock 
 */ 
$captchaBlock = $block->getLayout()->createBlock(\Magento\Captcha\Block\Captcha\DefaultCaptcha::class); 
$captchaBlock->setTemplate("Magento_Captcha::default.phtml"); 
$captchaBlock->setFormId("contact_us"); 
echo $captchaBlock->toHtml(); 
?>

The issue is that the captcha is not refreshing properly on my custom form. It works fine on the Contact Us page, but not on my custom form.

Any insights into why the captcha isn't refreshing correctly on my custom form would be greatly appreciated. Thank you!

1 Answer 1

1

You are mentioning the Magento_Captcha. To generate a new captcha for each request, this module requires the full page cache to be disabled.

If you review the layout XML files in the Magento_Captcha module, you will find it disables the full page cache by adding the cacheable="false" attribute. For example, here is the captcha block for the contact us page https://github.com/magento/magento2/blob/2.4.7/app/code/Magento/Captcha/view/frontend/layout/contact_index_index.xml#L11

<referenceContainer name="form.additional.info">
    <block class="Magento\Captcha\Block\Captcha" name="captcha" after="-" cacheable="false">
        <action method="setFormId">
            <argument name="formId" xsi:type="string">contact_us</argument>
        </action>
        <action method="setImgWidth">
            <argument name="width" xsi:type="string">230</argument>
        </action>
        <action method="setImgHeight">
            <argument name="width" xsi:type="string">50</argument>
        </action>
    </block>
</referenceContainer>

I believe you are talking about a custom page, rather than a static page. Static pages are created through the admin panel by navigating to the Admin menu > Content > Elements > Pages. If this is the case, please modify your XML layout file to add a captcha block similar to the one I previously mentioned for the contact page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.