Magento 2 - How to add captcha to a custom form The Next CEO of Stack OverflowMagento2 : How to use default captcha code in footer newsletter?Magento 2: How to display captcha on Custom Form?Magento 2 default captcha on newsletter form?Magento 2 : How to add Captcha in custom form Magento 2How to add Google Recaptcha to a custom newsletter subscribe form (which uses subscribe.phtml) on a CMS Page?Magento 2: How Captcha Module works?How to add captcha in product review form in magento2?captcha issue in custom form Magento2Magento 2.2.5 How to add google captcha to newsletter form without use any third party extensionMagento 2: implement your own captcha typeAdd standard captcha to registration pageMagento 2: How to display captcha on Custom Form?How to add captcha in product review form in magento2?Magento 2: Captcha overwrite fatal error on PHP 7Magento1.9 : How to add Captcha to custom formCAPTCHA form not visible, after applying themeCaptcha not show on RWD Custom themeIncorrect captcha error for custom formcaptcha issue in custom form Magento2
Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?
Solution of this Diophantine Equation
How do I solve this limit?
Does it take more energy to get to Venus or to Mars?
How should I support this large drywall patch?
Rotate a column
Trouble understanding the speech of overseas colleagues
How to be diplomatic in refusing to write code that breaches the privacy of our users
What makes a siege story/plot interesting?
A pseudo-riley?
Is HostGator storing my password in plaintext?
Whats the best way to handle refactoring a big file?
How easy is it to start Magic from scratch?
How to Reset Passwords on Multiple Websites Easily?
How do spells that require an ability check vs. the caster's spell save DC work?
Can a single photon have an energy density?
Why do remote companies require working in the US?
Explicit solution of a Hamiltonian system
What can we do to stop prior company from asking us questions?
How can I open an app using Terminal?
What is meant by a M next to a roman numeral?
Return of the Riley Riddles in Reverse
India just shot down a satellite from the ground. At what altitude range is the resulting debris field?
Grabbing quick drinks
Magento 2 - How to add captcha to a custom form
The Next CEO of Stack OverflowMagento2 : How to use default captcha code in footer newsletter?Magento 2: How to display captcha on Custom Form?Magento 2 default captcha on newsletter form?Magento 2 : How to add Captcha in custom form Magento 2How to add Google Recaptcha to a custom newsletter subscribe form (which uses subscribe.phtml) on a CMS Page?Magento 2: How Captcha Module works?How to add captcha in product review form in magento2?captcha issue in custom form Magento2Magento 2.2.5 How to add google captcha to newsletter form without use any third party extensionMagento 2: implement your own captcha typeAdd standard captcha to registration pageMagento 2: How to display captcha on Custom Form?How to add captcha in product review form in magento2?Magento 2: Captcha overwrite fatal error on PHP 7Magento1.9 : How to add Captcha to custom formCAPTCHA form not visible, after applying themeCaptcha not show on RWD Custom themeIncorrect captcha error for custom formcaptcha issue in custom form Magento2
I'm developing a custom module which contains a form submission. I would like to add a captcha to it. And we want to use the Magento default captcha library so that the captcha is consistent with the one in registration form.
magento2 captcha
add a comment |
I'm developing a custom module which contains a form submission. I would like to add a captcha to it. And we want to use the Magento default captcha library so that the captcha is consistent with the one in registration form.
magento2 captcha
add a comment |
I'm developing a custom module which contains a form submission. I would like to add a captcha to it. And we want to use the Magento default captcha library so that the captcha is consistent with the one in registration form.
magento2 captcha
I'm developing a custom module which contains a form submission. I would like to add a captcha to it. And we want to use the Magento default captcha library so that the captcha is consistent with the one in registration form.
magento2 captcha
magento2 captcha
asked Aug 26 '16 at 11:08
PaulPaul
1,82672662
1,82672662
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
You need follow some step for using magento captcha into custom module.
Step 1 : Vendor/Module/etc/config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<customer>
<captcha>
<shown_to_logged_in_user>
<custom_form>1</custom_form>
</shown_to_logged_in_user>
<always_for>
<custom_form>1</custom_form>
</always_for>
</captcha>
</customer>
<captcha translate="label">
<frontend>
<areas>
<custom_form>
<label>Custom Form</label>
</custom_form>
</areas>
</frontend>
</captcha>
</default>
</config>
Step 2: Goto 'Admin -> Stores -> Configuration -> Customer -> Customer Configuration -> Captcha' and configure. You can able to see new forms value 'Custom Form'
Step 3: Create Vendor/Module/view/frontend/layout/yourroutid_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Custom Form</title>
</head>
<body>
<referenceContainer name="content">
<block class="VendorModuleBlockCaptchaForm" name="contactForm" template="Vendor_Module::captchaform.phtml">
<container name="form.additional.info" label="Form Additional Info">
<block class="MagentoCaptchaBlockCaptcha" name="captcha" after="-" cacheable="false">
<action method="setFormId">
<argument name="formId" xsi:type="string">custom_form</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>
</container>
</block>
</referenceContainer>
<referenceBlock name="head.components">
<block class="MagentoFrameworkViewElementJsComponents" name="captcha_page_head_components" template="Magento_Captcha::js/components.phtml"/>
</referenceBlock>
</body>
</page>
Step 4: Vendor/Module/Block/CaptchaForm.php
namespace VendorModuleBlock;
class CaptchaForm extends MagentoFrameworkViewElementTemplate
public function getFormAction()
return $this->getUrl('yourroute/index/post', ['_secure' => true]);
Step 5: Vendor/Moduel/view/frontend/templates/captchaform.phtml
<form class="form contact"
action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
id="contact-form"
method="post"
data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
data-mage-init='"validation":'>
<fieldset class="fieldset">
<legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Write Us') ?></span></legend><br />
<div class="field name required">
<label class="label" for="name"><span><?php /* @escapeNotVerified */ echo __('Name') ?></span></label>
<div class="control">
<input name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Name') ?>" value="" class="input-text" type="text" data-validate="required:true"/>
</div>
</div>
<div class="field email required">
<label class="label" for="email"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
<div class="control">
<input name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="" class="input-text" type="email" data-validate="required:true, 'validate-email':true"/>
</div>
</div>
<?php echo $block->getChildHtml('form.additional.info'); ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>" class="action submit primary">
<span><?php /* @escapeNotVerified */ echo __('Submit') ?></span>
</button>
</div>
</div>
</form>
Now you can able to see captcha into your form. Now need to validation your captcha using observer. So I use post controller predispatch event for validation.
Step 6: Vendor/Module/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_yourroute_index_post">
<observer name="captcha_custom_form" instance="VendorModuleObserverCheckCustomFormObserver" />
</event>
</config>
Step 7: Vendor/Module/Observer/CheckCustomFormObserver.php
namespace VendorModuleObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkAppObjectManager;
use MagentoCaptchaObserverCaptchaStringResolver;
class CheckCustomFormObserver implements ObserverInterface
/**
* @var MagentoCaptchaHelperData
*/
protected $_helper;
/**
* @var MagentoFrameworkAppActionFlag
*/
protected $_actionFlag;
/**
* @var MagentoFrameworkMessageManagerInterface
*/
protected $messageManager;
/**
* @var MagentoFrameworkAppResponseRedirectInterface
*/
protected $redirect;
/**
* @var CaptchaStringResolver
*/
protected $captchaStringResolver;
/**
* @var DataPersistorInterface
*/
private $dataPersistor;
/**
* @param MagentoCaptchaHelperData $helper
* @param MagentoFrameworkAppActionFlag $actionFlag
* @param MagentoFrameworkMessageManagerInterface $messageManager
* @param MagentoFrameworkAppResponseRedirectInterface $redirect
* @param CaptchaStringResolver $captchaStringResolver
*/
public function __construct(
MagentoCaptchaHelperData $helper,
MagentoFrameworkAppActionFlag $actionFlag,
MagentoFrameworkMessageManagerInterface $messageManager,
MagentoFrameworkAppResponseRedirectInterface $redirect,
CaptchaStringResolver $captchaStringResolver
)
$this->_helper = $helper;
$this->_actionFlag = $actionFlag;
$this->messageManager = $messageManager;
$this->redirect = $redirect;
$this->captchaStringResolver = $captchaStringResolver;
/**
* Check CAPTCHA on Custom Form
*
* @param MagentoFrameworkEventObserver $observer
* @return void
*/
public function execute(MagentoFrameworkEventObserver $observer)
$formId = 'custom_form';
$captcha = $this->_helper->getCaptcha($formId);
if ($captcha->isRequired())
/** @var MagentoFrameworkAppActionAction $controller */
$controller = $observer->getControllerAction();
if (!$captcha->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId)))
$this->messageManager->addError(__('Incorrect CAPTCHA.'));
$this->getDataPersistor()->set($formId, $controller->getRequest()->getPostValue());
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$this->redirect->redirect($controller->getResponse(), 'yourroute/index/index');
/**
* Get Data Persistor
*
* @return DataPersistorInterface
*/
private function getDataPersistor()
if ($this->dataPersistor === null)
$this->dataPersistor = ObjectManager::getInstance()
->get(DataPersistorInterface::class);
return $this->dataPersistor;
Very detailed. I will try it out.
– Paul
Sep 5 '16 at 15:53
@Sohel Rana how can be add it into product review form
– supriya mishra
Jan 12 '17 at 5:57
@supriyamishra need to check
– Sohel Rana
Jan 12 '17 at 6:19
1
Hi The captcha is displayed but the observer controller_action_predispatch_** is i think not working as this captcha is not being validated
– AbdulBasit
Feb 20 '18 at 12:06
1
I resolved above error but i can't see the captcha in my custom form
– jafar pinjar
Aug 22 '18 at 6:59
|
show 12 more comments
For those of you that cannot get this to work you may need to do what I did:
The reason you captcha may not be displaying is because the base settings are to use the Default captcha block which in the _toHtml does a check to see if the captcha is required.
If you have you settings for captcha to always show than you probably did not run into this issue however if it is not set to always show captchas and you do not want to always show captchas (ie account create/ login etc) than you need to set the logic for only your custom captcha to "Always be required".
on line 69 of vendor/magento/module-captcha/Block/Captcha/DefaultCaptcha.php you will see:
/**
* Renders captcha HTML (if required)
*
* @return string
*/
protected function _toHtml()
if ($this->getCaptchaModel()->isRequired())
$this->getCaptchaModel()->generate();
return parent::_toHtml();
return '';
$this->getCaptchaModel() calls $this->_captchaData->getCaptcha() which is in
vendor/magento/module-captcha/Helper/Data.php
/**
* Get Captcha
*
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
*/
public function getCaptcha($formId)
if (!array_key_exists($formId, $this->_captcha))
$captchaType = ucfirst($this->getConfig('type'));
if (!$captchaType)
$captchaType = self::DEFAULT_CAPTCHA_TYPE;
elseif ($captchaType == 'Default')
$captchaType = $captchaType . 'Model';
$this->_captcha[$formId] = $this->_factory->create($captchaType, $formId);
return $this->_captcha[$formId];
Here the getCaptcha method checks the config value for the type of captcha to render and loads its factory in with $this->_factory->create()
However stepping into this factory class you will see
public function create($captchaType, $formId)
$className = 'MagentoCaptchaModel\' . ucfirst($captchaType);
$instance = $this->_objectManager->create($className, ['formId' => $formId]);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
$className . ' does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
The issue here is that no matter what the factory will look in the Magento Captcha module for any Factory model.. so
We need to create a plugin to wrap around the helper and check for our form key and if it is our form key being used we need to create a new factory class that loads our model that extends MagentoCaptchaModelDefaultModel and overides the isRequired() method. Something that looks like this:
in YourModuleetcdi.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!--Custom Captcha-->
<type name="MagentoCaptchaHelperData">
<plugin name="custom-captcha" type="YourModulePluginHelperCaptchaData" />
</type>
in YourModulePluginHelperCaptchaData
<?php
namespace YourModulePluginHelper;
class CaptchaData
protected $_captcha = [];
public function __construct(
YourModuleModelCaptchaFactory $captchaFactory
)
$this->captchaFactory = $captchaFactory;
/**
* @param MagentoCaptchaHelperData $subject
* @param Closure $proceed
* @param $formId
* @return mixed
*/
public function aroundGetCaptcha(MagentoCaptchaHelperData $subject, Closure $proceed, $formId)
if ($formId == 'your_form_key')
$this->_captcha[$formId] = $this->captchaFactory->create();
return $this->_captcha[$formId];
return $proceed($formId);
in YourModuleModelCaptchaFactory
<?php
/**
* Captcha model factory
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace YourModuleModel;
class CaptchaFactory
/**
* @var MagentoFrameworkObjectManagerInterface
*/
protected $_objectManager;
/**
* @param MagentoFrameworkObjectManagerInterface $objectManager
*/
public function __construct(MagentoFrameworkObjectManagerInterface $objectManager)
$this->_objectManager = $objectManager;
/**
* Get captcha instance
*
* @param string $captchaType
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
* @throws InvalidArgumentException
*/
public function create()
$instance = $this->_objectManager->create('YourModuleModelCaptcha', ['formId' => 'event_subscriber']);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
'YourModuleModelCaptcha does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
and finally your model to overide the is required param in
YourModuleModelCaptcha:
<?php
namespace YourModuleModel;
class Captcha extends MagentoCaptchaModelDefaultModel
public function isRequired($login = null)
return true;
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f133238%2fmagento-2-how-to-add-captcha-to-a-custom-form%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You need follow some step for using magento captcha into custom module.
Step 1 : Vendor/Module/etc/config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<customer>
<captcha>
<shown_to_logged_in_user>
<custom_form>1</custom_form>
</shown_to_logged_in_user>
<always_for>
<custom_form>1</custom_form>
</always_for>
</captcha>
</customer>
<captcha translate="label">
<frontend>
<areas>
<custom_form>
<label>Custom Form</label>
</custom_form>
</areas>
</frontend>
</captcha>
</default>
</config>
Step 2: Goto 'Admin -> Stores -> Configuration -> Customer -> Customer Configuration -> Captcha' and configure. You can able to see new forms value 'Custom Form'
Step 3: Create Vendor/Module/view/frontend/layout/yourroutid_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Custom Form</title>
</head>
<body>
<referenceContainer name="content">
<block class="VendorModuleBlockCaptchaForm" name="contactForm" template="Vendor_Module::captchaform.phtml">
<container name="form.additional.info" label="Form Additional Info">
<block class="MagentoCaptchaBlockCaptcha" name="captcha" after="-" cacheable="false">
<action method="setFormId">
<argument name="formId" xsi:type="string">custom_form</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>
</container>
</block>
</referenceContainer>
<referenceBlock name="head.components">
<block class="MagentoFrameworkViewElementJsComponents" name="captcha_page_head_components" template="Magento_Captcha::js/components.phtml"/>
</referenceBlock>
</body>
</page>
Step 4: Vendor/Module/Block/CaptchaForm.php
namespace VendorModuleBlock;
class CaptchaForm extends MagentoFrameworkViewElementTemplate
public function getFormAction()
return $this->getUrl('yourroute/index/post', ['_secure' => true]);
Step 5: Vendor/Moduel/view/frontend/templates/captchaform.phtml
<form class="form contact"
action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
id="contact-form"
method="post"
data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
data-mage-init='"validation":'>
<fieldset class="fieldset">
<legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Write Us') ?></span></legend><br />
<div class="field name required">
<label class="label" for="name"><span><?php /* @escapeNotVerified */ echo __('Name') ?></span></label>
<div class="control">
<input name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Name') ?>" value="" class="input-text" type="text" data-validate="required:true"/>
</div>
</div>
<div class="field email required">
<label class="label" for="email"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
<div class="control">
<input name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="" class="input-text" type="email" data-validate="required:true, 'validate-email':true"/>
</div>
</div>
<?php echo $block->getChildHtml('form.additional.info'); ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>" class="action submit primary">
<span><?php /* @escapeNotVerified */ echo __('Submit') ?></span>
</button>
</div>
</div>
</form>
Now you can able to see captcha into your form. Now need to validation your captcha using observer. So I use post controller predispatch event for validation.
Step 6: Vendor/Module/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_yourroute_index_post">
<observer name="captcha_custom_form" instance="VendorModuleObserverCheckCustomFormObserver" />
</event>
</config>
Step 7: Vendor/Module/Observer/CheckCustomFormObserver.php
namespace VendorModuleObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkAppObjectManager;
use MagentoCaptchaObserverCaptchaStringResolver;
class CheckCustomFormObserver implements ObserverInterface
/**
* @var MagentoCaptchaHelperData
*/
protected $_helper;
/**
* @var MagentoFrameworkAppActionFlag
*/
protected $_actionFlag;
/**
* @var MagentoFrameworkMessageManagerInterface
*/
protected $messageManager;
/**
* @var MagentoFrameworkAppResponseRedirectInterface
*/
protected $redirect;
/**
* @var CaptchaStringResolver
*/
protected $captchaStringResolver;
/**
* @var DataPersistorInterface
*/
private $dataPersistor;
/**
* @param MagentoCaptchaHelperData $helper
* @param MagentoFrameworkAppActionFlag $actionFlag
* @param MagentoFrameworkMessageManagerInterface $messageManager
* @param MagentoFrameworkAppResponseRedirectInterface $redirect
* @param CaptchaStringResolver $captchaStringResolver
*/
public function __construct(
MagentoCaptchaHelperData $helper,
MagentoFrameworkAppActionFlag $actionFlag,
MagentoFrameworkMessageManagerInterface $messageManager,
MagentoFrameworkAppResponseRedirectInterface $redirect,
CaptchaStringResolver $captchaStringResolver
)
$this->_helper = $helper;
$this->_actionFlag = $actionFlag;
$this->messageManager = $messageManager;
$this->redirect = $redirect;
$this->captchaStringResolver = $captchaStringResolver;
/**
* Check CAPTCHA on Custom Form
*
* @param MagentoFrameworkEventObserver $observer
* @return void
*/
public function execute(MagentoFrameworkEventObserver $observer)
$formId = 'custom_form';
$captcha = $this->_helper->getCaptcha($formId);
if ($captcha->isRequired())
/** @var MagentoFrameworkAppActionAction $controller */
$controller = $observer->getControllerAction();
if (!$captcha->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId)))
$this->messageManager->addError(__('Incorrect CAPTCHA.'));
$this->getDataPersistor()->set($formId, $controller->getRequest()->getPostValue());
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$this->redirect->redirect($controller->getResponse(), 'yourroute/index/index');
/**
* Get Data Persistor
*
* @return DataPersistorInterface
*/
private function getDataPersistor()
if ($this->dataPersistor === null)
$this->dataPersistor = ObjectManager::getInstance()
->get(DataPersistorInterface::class);
return $this->dataPersistor;
Very detailed. I will try it out.
– Paul
Sep 5 '16 at 15:53
@Sohel Rana how can be add it into product review form
– supriya mishra
Jan 12 '17 at 5:57
@supriyamishra need to check
– Sohel Rana
Jan 12 '17 at 6:19
1
Hi The captcha is displayed but the observer controller_action_predispatch_** is i think not working as this captcha is not being validated
– AbdulBasit
Feb 20 '18 at 12:06
1
I resolved above error but i can't see the captcha in my custom form
– jafar pinjar
Aug 22 '18 at 6:59
|
show 12 more comments
You need follow some step for using magento captcha into custom module.
Step 1 : Vendor/Module/etc/config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<customer>
<captcha>
<shown_to_logged_in_user>
<custom_form>1</custom_form>
</shown_to_logged_in_user>
<always_for>
<custom_form>1</custom_form>
</always_for>
</captcha>
</customer>
<captcha translate="label">
<frontend>
<areas>
<custom_form>
<label>Custom Form</label>
</custom_form>
</areas>
</frontend>
</captcha>
</default>
</config>
Step 2: Goto 'Admin -> Stores -> Configuration -> Customer -> Customer Configuration -> Captcha' and configure. You can able to see new forms value 'Custom Form'
Step 3: Create Vendor/Module/view/frontend/layout/yourroutid_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Custom Form</title>
</head>
<body>
<referenceContainer name="content">
<block class="VendorModuleBlockCaptchaForm" name="contactForm" template="Vendor_Module::captchaform.phtml">
<container name="form.additional.info" label="Form Additional Info">
<block class="MagentoCaptchaBlockCaptcha" name="captcha" after="-" cacheable="false">
<action method="setFormId">
<argument name="formId" xsi:type="string">custom_form</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>
</container>
</block>
</referenceContainer>
<referenceBlock name="head.components">
<block class="MagentoFrameworkViewElementJsComponents" name="captcha_page_head_components" template="Magento_Captcha::js/components.phtml"/>
</referenceBlock>
</body>
</page>
Step 4: Vendor/Module/Block/CaptchaForm.php
namespace VendorModuleBlock;
class CaptchaForm extends MagentoFrameworkViewElementTemplate
public function getFormAction()
return $this->getUrl('yourroute/index/post', ['_secure' => true]);
Step 5: Vendor/Moduel/view/frontend/templates/captchaform.phtml
<form class="form contact"
action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
id="contact-form"
method="post"
data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
data-mage-init='"validation":'>
<fieldset class="fieldset">
<legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Write Us') ?></span></legend><br />
<div class="field name required">
<label class="label" for="name"><span><?php /* @escapeNotVerified */ echo __('Name') ?></span></label>
<div class="control">
<input name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Name') ?>" value="" class="input-text" type="text" data-validate="required:true"/>
</div>
</div>
<div class="field email required">
<label class="label" for="email"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
<div class="control">
<input name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="" class="input-text" type="email" data-validate="required:true, 'validate-email':true"/>
</div>
</div>
<?php echo $block->getChildHtml('form.additional.info'); ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>" class="action submit primary">
<span><?php /* @escapeNotVerified */ echo __('Submit') ?></span>
</button>
</div>
</div>
</form>
Now you can able to see captcha into your form. Now need to validation your captcha using observer. So I use post controller predispatch event for validation.
Step 6: Vendor/Module/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_yourroute_index_post">
<observer name="captcha_custom_form" instance="VendorModuleObserverCheckCustomFormObserver" />
</event>
</config>
Step 7: Vendor/Module/Observer/CheckCustomFormObserver.php
namespace VendorModuleObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkAppObjectManager;
use MagentoCaptchaObserverCaptchaStringResolver;
class CheckCustomFormObserver implements ObserverInterface
/**
* @var MagentoCaptchaHelperData
*/
protected $_helper;
/**
* @var MagentoFrameworkAppActionFlag
*/
protected $_actionFlag;
/**
* @var MagentoFrameworkMessageManagerInterface
*/
protected $messageManager;
/**
* @var MagentoFrameworkAppResponseRedirectInterface
*/
protected $redirect;
/**
* @var CaptchaStringResolver
*/
protected $captchaStringResolver;
/**
* @var DataPersistorInterface
*/
private $dataPersistor;
/**
* @param MagentoCaptchaHelperData $helper
* @param MagentoFrameworkAppActionFlag $actionFlag
* @param MagentoFrameworkMessageManagerInterface $messageManager
* @param MagentoFrameworkAppResponseRedirectInterface $redirect
* @param CaptchaStringResolver $captchaStringResolver
*/
public function __construct(
MagentoCaptchaHelperData $helper,
MagentoFrameworkAppActionFlag $actionFlag,
MagentoFrameworkMessageManagerInterface $messageManager,
MagentoFrameworkAppResponseRedirectInterface $redirect,
CaptchaStringResolver $captchaStringResolver
)
$this->_helper = $helper;
$this->_actionFlag = $actionFlag;
$this->messageManager = $messageManager;
$this->redirect = $redirect;
$this->captchaStringResolver = $captchaStringResolver;
/**
* Check CAPTCHA on Custom Form
*
* @param MagentoFrameworkEventObserver $observer
* @return void
*/
public function execute(MagentoFrameworkEventObserver $observer)
$formId = 'custom_form';
$captcha = $this->_helper->getCaptcha($formId);
if ($captcha->isRequired())
/** @var MagentoFrameworkAppActionAction $controller */
$controller = $observer->getControllerAction();
if (!$captcha->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId)))
$this->messageManager->addError(__('Incorrect CAPTCHA.'));
$this->getDataPersistor()->set($formId, $controller->getRequest()->getPostValue());
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$this->redirect->redirect($controller->getResponse(), 'yourroute/index/index');
/**
* Get Data Persistor
*
* @return DataPersistorInterface
*/
private function getDataPersistor()
if ($this->dataPersistor === null)
$this->dataPersistor = ObjectManager::getInstance()
->get(DataPersistorInterface::class);
return $this->dataPersistor;
Very detailed. I will try it out.
– Paul
Sep 5 '16 at 15:53
@Sohel Rana how can be add it into product review form
– supriya mishra
Jan 12 '17 at 5:57
@supriyamishra need to check
– Sohel Rana
Jan 12 '17 at 6:19
1
Hi The captcha is displayed but the observer controller_action_predispatch_** is i think not working as this captcha is not being validated
– AbdulBasit
Feb 20 '18 at 12:06
1
I resolved above error but i can't see the captcha in my custom form
– jafar pinjar
Aug 22 '18 at 6:59
|
show 12 more comments
You need follow some step for using magento captcha into custom module.
Step 1 : Vendor/Module/etc/config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<customer>
<captcha>
<shown_to_logged_in_user>
<custom_form>1</custom_form>
</shown_to_logged_in_user>
<always_for>
<custom_form>1</custom_form>
</always_for>
</captcha>
</customer>
<captcha translate="label">
<frontend>
<areas>
<custom_form>
<label>Custom Form</label>
</custom_form>
</areas>
</frontend>
</captcha>
</default>
</config>
Step 2: Goto 'Admin -> Stores -> Configuration -> Customer -> Customer Configuration -> Captcha' and configure. You can able to see new forms value 'Custom Form'
Step 3: Create Vendor/Module/view/frontend/layout/yourroutid_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Custom Form</title>
</head>
<body>
<referenceContainer name="content">
<block class="VendorModuleBlockCaptchaForm" name="contactForm" template="Vendor_Module::captchaform.phtml">
<container name="form.additional.info" label="Form Additional Info">
<block class="MagentoCaptchaBlockCaptcha" name="captcha" after="-" cacheable="false">
<action method="setFormId">
<argument name="formId" xsi:type="string">custom_form</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>
</container>
</block>
</referenceContainer>
<referenceBlock name="head.components">
<block class="MagentoFrameworkViewElementJsComponents" name="captcha_page_head_components" template="Magento_Captcha::js/components.phtml"/>
</referenceBlock>
</body>
</page>
Step 4: Vendor/Module/Block/CaptchaForm.php
namespace VendorModuleBlock;
class CaptchaForm extends MagentoFrameworkViewElementTemplate
public function getFormAction()
return $this->getUrl('yourroute/index/post', ['_secure' => true]);
Step 5: Vendor/Moduel/view/frontend/templates/captchaform.phtml
<form class="form contact"
action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
id="contact-form"
method="post"
data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
data-mage-init='"validation":'>
<fieldset class="fieldset">
<legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Write Us') ?></span></legend><br />
<div class="field name required">
<label class="label" for="name"><span><?php /* @escapeNotVerified */ echo __('Name') ?></span></label>
<div class="control">
<input name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Name') ?>" value="" class="input-text" type="text" data-validate="required:true"/>
</div>
</div>
<div class="field email required">
<label class="label" for="email"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
<div class="control">
<input name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="" class="input-text" type="email" data-validate="required:true, 'validate-email':true"/>
</div>
</div>
<?php echo $block->getChildHtml('form.additional.info'); ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>" class="action submit primary">
<span><?php /* @escapeNotVerified */ echo __('Submit') ?></span>
</button>
</div>
</div>
</form>
Now you can able to see captcha into your form. Now need to validation your captcha using observer. So I use post controller predispatch event for validation.
Step 6: Vendor/Module/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_yourroute_index_post">
<observer name="captcha_custom_form" instance="VendorModuleObserverCheckCustomFormObserver" />
</event>
</config>
Step 7: Vendor/Module/Observer/CheckCustomFormObserver.php
namespace VendorModuleObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkAppObjectManager;
use MagentoCaptchaObserverCaptchaStringResolver;
class CheckCustomFormObserver implements ObserverInterface
/**
* @var MagentoCaptchaHelperData
*/
protected $_helper;
/**
* @var MagentoFrameworkAppActionFlag
*/
protected $_actionFlag;
/**
* @var MagentoFrameworkMessageManagerInterface
*/
protected $messageManager;
/**
* @var MagentoFrameworkAppResponseRedirectInterface
*/
protected $redirect;
/**
* @var CaptchaStringResolver
*/
protected $captchaStringResolver;
/**
* @var DataPersistorInterface
*/
private $dataPersistor;
/**
* @param MagentoCaptchaHelperData $helper
* @param MagentoFrameworkAppActionFlag $actionFlag
* @param MagentoFrameworkMessageManagerInterface $messageManager
* @param MagentoFrameworkAppResponseRedirectInterface $redirect
* @param CaptchaStringResolver $captchaStringResolver
*/
public function __construct(
MagentoCaptchaHelperData $helper,
MagentoFrameworkAppActionFlag $actionFlag,
MagentoFrameworkMessageManagerInterface $messageManager,
MagentoFrameworkAppResponseRedirectInterface $redirect,
CaptchaStringResolver $captchaStringResolver
)
$this->_helper = $helper;
$this->_actionFlag = $actionFlag;
$this->messageManager = $messageManager;
$this->redirect = $redirect;
$this->captchaStringResolver = $captchaStringResolver;
/**
* Check CAPTCHA on Custom Form
*
* @param MagentoFrameworkEventObserver $observer
* @return void
*/
public function execute(MagentoFrameworkEventObserver $observer)
$formId = 'custom_form';
$captcha = $this->_helper->getCaptcha($formId);
if ($captcha->isRequired())
/** @var MagentoFrameworkAppActionAction $controller */
$controller = $observer->getControllerAction();
if (!$captcha->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId)))
$this->messageManager->addError(__('Incorrect CAPTCHA.'));
$this->getDataPersistor()->set($formId, $controller->getRequest()->getPostValue());
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$this->redirect->redirect($controller->getResponse(), 'yourroute/index/index');
/**
* Get Data Persistor
*
* @return DataPersistorInterface
*/
private function getDataPersistor()
if ($this->dataPersistor === null)
$this->dataPersistor = ObjectManager::getInstance()
->get(DataPersistorInterface::class);
return $this->dataPersistor;
You need follow some step for using magento captcha into custom module.
Step 1 : Vendor/Module/etc/config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<customer>
<captcha>
<shown_to_logged_in_user>
<custom_form>1</custom_form>
</shown_to_logged_in_user>
<always_for>
<custom_form>1</custom_form>
</always_for>
</captcha>
</customer>
<captcha translate="label">
<frontend>
<areas>
<custom_form>
<label>Custom Form</label>
</custom_form>
</areas>
</frontend>
</captcha>
</default>
</config>
Step 2: Goto 'Admin -> Stores -> Configuration -> Customer -> Customer Configuration -> Captcha' and configure. You can able to see new forms value 'Custom Form'
Step 3: Create Vendor/Module/view/frontend/layout/yourroutid_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Custom Form</title>
</head>
<body>
<referenceContainer name="content">
<block class="VendorModuleBlockCaptchaForm" name="contactForm" template="Vendor_Module::captchaform.phtml">
<container name="form.additional.info" label="Form Additional Info">
<block class="MagentoCaptchaBlockCaptcha" name="captcha" after="-" cacheable="false">
<action method="setFormId">
<argument name="formId" xsi:type="string">custom_form</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>
</container>
</block>
</referenceContainer>
<referenceBlock name="head.components">
<block class="MagentoFrameworkViewElementJsComponents" name="captcha_page_head_components" template="Magento_Captcha::js/components.phtml"/>
</referenceBlock>
</body>
</page>
Step 4: Vendor/Module/Block/CaptchaForm.php
namespace VendorModuleBlock;
class CaptchaForm extends MagentoFrameworkViewElementTemplate
public function getFormAction()
return $this->getUrl('yourroute/index/post', ['_secure' => true]);
Step 5: Vendor/Moduel/view/frontend/templates/captchaform.phtml
<form class="form contact"
action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
id="contact-form"
method="post"
data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
data-mage-init='"validation":'>
<fieldset class="fieldset">
<legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Write Us') ?></span></legend><br />
<div class="field name required">
<label class="label" for="name"><span><?php /* @escapeNotVerified */ echo __('Name') ?></span></label>
<div class="control">
<input name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Name') ?>" value="" class="input-text" type="text" data-validate="required:true"/>
</div>
</div>
<div class="field email required">
<label class="label" for="email"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
<div class="control">
<input name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="" class="input-text" type="email" data-validate="required:true, 'validate-email':true"/>
</div>
</div>
<?php echo $block->getChildHtml('form.additional.info'); ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>" class="action submit primary">
<span><?php /* @escapeNotVerified */ echo __('Submit') ?></span>
</button>
</div>
</div>
</form>
Now you can able to see captcha into your form. Now need to validation your captcha using observer. So I use post controller predispatch event for validation.
Step 6: Vendor/Module/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_yourroute_index_post">
<observer name="captcha_custom_form" instance="VendorModuleObserverCheckCustomFormObserver" />
</event>
</config>
Step 7: Vendor/Module/Observer/CheckCustomFormObserver.php
namespace VendorModuleObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkAppObjectManager;
use MagentoCaptchaObserverCaptchaStringResolver;
class CheckCustomFormObserver implements ObserverInterface
/**
* @var MagentoCaptchaHelperData
*/
protected $_helper;
/**
* @var MagentoFrameworkAppActionFlag
*/
protected $_actionFlag;
/**
* @var MagentoFrameworkMessageManagerInterface
*/
protected $messageManager;
/**
* @var MagentoFrameworkAppResponseRedirectInterface
*/
protected $redirect;
/**
* @var CaptchaStringResolver
*/
protected $captchaStringResolver;
/**
* @var DataPersistorInterface
*/
private $dataPersistor;
/**
* @param MagentoCaptchaHelperData $helper
* @param MagentoFrameworkAppActionFlag $actionFlag
* @param MagentoFrameworkMessageManagerInterface $messageManager
* @param MagentoFrameworkAppResponseRedirectInterface $redirect
* @param CaptchaStringResolver $captchaStringResolver
*/
public function __construct(
MagentoCaptchaHelperData $helper,
MagentoFrameworkAppActionFlag $actionFlag,
MagentoFrameworkMessageManagerInterface $messageManager,
MagentoFrameworkAppResponseRedirectInterface $redirect,
CaptchaStringResolver $captchaStringResolver
)
$this->_helper = $helper;
$this->_actionFlag = $actionFlag;
$this->messageManager = $messageManager;
$this->redirect = $redirect;
$this->captchaStringResolver = $captchaStringResolver;
/**
* Check CAPTCHA on Custom Form
*
* @param MagentoFrameworkEventObserver $observer
* @return void
*/
public function execute(MagentoFrameworkEventObserver $observer)
$formId = 'custom_form';
$captcha = $this->_helper->getCaptcha($formId);
if ($captcha->isRequired())
/** @var MagentoFrameworkAppActionAction $controller */
$controller = $observer->getControllerAction();
if (!$captcha->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId)))
$this->messageManager->addError(__('Incorrect CAPTCHA.'));
$this->getDataPersistor()->set($formId, $controller->getRequest()->getPostValue());
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$this->redirect->redirect($controller->getResponse(), 'yourroute/index/index');
/**
* Get Data Persistor
*
* @return DataPersistorInterface
*/
private function getDataPersistor()
if ($this->dataPersistor === null)
$this->dataPersistor = ObjectManager::getInstance()
->get(DataPersistorInterface::class);
return $this->dataPersistor;
edited Jun 25 '18 at 7:26
Rohan Hapani
6,76331865
6,76331865
answered Aug 28 '16 at 9:51
Sohel RanaSohel Rana
22.9k34460
22.9k34460
Very detailed. I will try it out.
– Paul
Sep 5 '16 at 15:53
@Sohel Rana how can be add it into product review form
– supriya mishra
Jan 12 '17 at 5:57
@supriyamishra need to check
– Sohel Rana
Jan 12 '17 at 6:19
1
Hi The captcha is displayed but the observer controller_action_predispatch_** is i think not working as this captcha is not being validated
– AbdulBasit
Feb 20 '18 at 12:06
1
I resolved above error but i can't see the captcha in my custom form
– jafar pinjar
Aug 22 '18 at 6:59
|
show 12 more comments
Very detailed. I will try it out.
– Paul
Sep 5 '16 at 15:53
@Sohel Rana how can be add it into product review form
– supriya mishra
Jan 12 '17 at 5:57
@supriyamishra need to check
– Sohel Rana
Jan 12 '17 at 6:19
1
Hi The captcha is displayed but the observer controller_action_predispatch_** is i think not working as this captcha is not being validated
– AbdulBasit
Feb 20 '18 at 12:06
1
I resolved above error but i can't see the captcha in my custom form
– jafar pinjar
Aug 22 '18 at 6:59
Very detailed. I will try it out.
– Paul
Sep 5 '16 at 15:53
Very detailed. I will try it out.
– Paul
Sep 5 '16 at 15:53
@Sohel Rana how can be add it into product review form
– supriya mishra
Jan 12 '17 at 5:57
@Sohel Rana how can be add it into product review form
– supriya mishra
Jan 12 '17 at 5:57
@supriyamishra need to check
– Sohel Rana
Jan 12 '17 at 6:19
@supriyamishra need to check
– Sohel Rana
Jan 12 '17 at 6:19
1
1
Hi The captcha is displayed but the observer controller_action_predispatch_** is i think not working as this captcha is not being validated
– AbdulBasit
Feb 20 '18 at 12:06
Hi The captcha is displayed but the observer controller_action_predispatch_** is i think not working as this captcha is not being validated
– AbdulBasit
Feb 20 '18 at 12:06
1
1
I resolved above error but i can't see the captcha in my custom form
– jafar pinjar
Aug 22 '18 at 6:59
I resolved above error but i can't see the captcha in my custom form
– jafar pinjar
Aug 22 '18 at 6:59
|
show 12 more comments
For those of you that cannot get this to work you may need to do what I did:
The reason you captcha may not be displaying is because the base settings are to use the Default captcha block which in the _toHtml does a check to see if the captcha is required.
If you have you settings for captcha to always show than you probably did not run into this issue however if it is not set to always show captchas and you do not want to always show captchas (ie account create/ login etc) than you need to set the logic for only your custom captcha to "Always be required".
on line 69 of vendor/magento/module-captcha/Block/Captcha/DefaultCaptcha.php you will see:
/**
* Renders captcha HTML (if required)
*
* @return string
*/
protected function _toHtml()
if ($this->getCaptchaModel()->isRequired())
$this->getCaptchaModel()->generate();
return parent::_toHtml();
return '';
$this->getCaptchaModel() calls $this->_captchaData->getCaptcha() which is in
vendor/magento/module-captcha/Helper/Data.php
/**
* Get Captcha
*
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
*/
public function getCaptcha($formId)
if (!array_key_exists($formId, $this->_captcha))
$captchaType = ucfirst($this->getConfig('type'));
if (!$captchaType)
$captchaType = self::DEFAULT_CAPTCHA_TYPE;
elseif ($captchaType == 'Default')
$captchaType = $captchaType . 'Model';
$this->_captcha[$formId] = $this->_factory->create($captchaType, $formId);
return $this->_captcha[$formId];
Here the getCaptcha method checks the config value for the type of captcha to render and loads its factory in with $this->_factory->create()
However stepping into this factory class you will see
public function create($captchaType, $formId)
$className = 'MagentoCaptchaModel\' . ucfirst($captchaType);
$instance = $this->_objectManager->create($className, ['formId' => $formId]);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
$className . ' does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
The issue here is that no matter what the factory will look in the Magento Captcha module for any Factory model.. so
We need to create a plugin to wrap around the helper and check for our form key and if it is our form key being used we need to create a new factory class that loads our model that extends MagentoCaptchaModelDefaultModel and overides the isRequired() method. Something that looks like this:
in YourModuleetcdi.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!--Custom Captcha-->
<type name="MagentoCaptchaHelperData">
<plugin name="custom-captcha" type="YourModulePluginHelperCaptchaData" />
</type>
in YourModulePluginHelperCaptchaData
<?php
namespace YourModulePluginHelper;
class CaptchaData
protected $_captcha = [];
public function __construct(
YourModuleModelCaptchaFactory $captchaFactory
)
$this->captchaFactory = $captchaFactory;
/**
* @param MagentoCaptchaHelperData $subject
* @param Closure $proceed
* @param $formId
* @return mixed
*/
public function aroundGetCaptcha(MagentoCaptchaHelperData $subject, Closure $proceed, $formId)
if ($formId == 'your_form_key')
$this->_captcha[$formId] = $this->captchaFactory->create();
return $this->_captcha[$formId];
return $proceed($formId);
in YourModuleModelCaptchaFactory
<?php
/**
* Captcha model factory
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace YourModuleModel;
class CaptchaFactory
/**
* @var MagentoFrameworkObjectManagerInterface
*/
protected $_objectManager;
/**
* @param MagentoFrameworkObjectManagerInterface $objectManager
*/
public function __construct(MagentoFrameworkObjectManagerInterface $objectManager)
$this->_objectManager = $objectManager;
/**
* Get captcha instance
*
* @param string $captchaType
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
* @throws InvalidArgumentException
*/
public function create()
$instance = $this->_objectManager->create('YourModuleModelCaptcha', ['formId' => 'event_subscriber']);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
'YourModuleModelCaptcha does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
and finally your model to overide the is required param in
YourModuleModelCaptcha:
<?php
namespace YourModuleModel;
class Captcha extends MagentoCaptchaModelDefaultModel
public function isRequired($login = null)
return true;
add a comment |
For those of you that cannot get this to work you may need to do what I did:
The reason you captcha may not be displaying is because the base settings are to use the Default captcha block which in the _toHtml does a check to see if the captcha is required.
If you have you settings for captcha to always show than you probably did not run into this issue however if it is not set to always show captchas and you do not want to always show captchas (ie account create/ login etc) than you need to set the logic for only your custom captcha to "Always be required".
on line 69 of vendor/magento/module-captcha/Block/Captcha/DefaultCaptcha.php you will see:
/**
* Renders captcha HTML (if required)
*
* @return string
*/
protected function _toHtml()
if ($this->getCaptchaModel()->isRequired())
$this->getCaptchaModel()->generate();
return parent::_toHtml();
return '';
$this->getCaptchaModel() calls $this->_captchaData->getCaptcha() which is in
vendor/magento/module-captcha/Helper/Data.php
/**
* Get Captcha
*
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
*/
public function getCaptcha($formId)
if (!array_key_exists($formId, $this->_captcha))
$captchaType = ucfirst($this->getConfig('type'));
if (!$captchaType)
$captchaType = self::DEFAULT_CAPTCHA_TYPE;
elseif ($captchaType == 'Default')
$captchaType = $captchaType . 'Model';
$this->_captcha[$formId] = $this->_factory->create($captchaType, $formId);
return $this->_captcha[$formId];
Here the getCaptcha method checks the config value for the type of captcha to render and loads its factory in with $this->_factory->create()
However stepping into this factory class you will see
public function create($captchaType, $formId)
$className = 'MagentoCaptchaModel\' . ucfirst($captchaType);
$instance = $this->_objectManager->create($className, ['formId' => $formId]);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
$className . ' does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
The issue here is that no matter what the factory will look in the Magento Captcha module for any Factory model.. so
We need to create a plugin to wrap around the helper and check for our form key and if it is our form key being used we need to create a new factory class that loads our model that extends MagentoCaptchaModelDefaultModel and overides the isRequired() method. Something that looks like this:
in YourModuleetcdi.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!--Custom Captcha-->
<type name="MagentoCaptchaHelperData">
<plugin name="custom-captcha" type="YourModulePluginHelperCaptchaData" />
</type>
in YourModulePluginHelperCaptchaData
<?php
namespace YourModulePluginHelper;
class CaptchaData
protected $_captcha = [];
public function __construct(
YourModuleModelCaptchaFactory $captchaFactory
)
$this->captchaFactory = $captchaFactory;
/**
* @param MagentoCaptchaHelperData $subject
* @param Closure $proceed
* @param $formId
* @return mixed
*/
public function aroundGetCaptcha(MagentoCaptchaHelperData $subject, Closure $proceed, $formId)
if ($formId == 'your_form_key')
$this->_captcha[$formId] = $this->captchaFactory->create();
return $this->_captcha[$formId];
return $proceed($formId);
in YourModuleModelCaptchaFactory
<?php
/**
* Captcha model factory
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace YourModuleModel;
class CaptchaFactory
/**
* @var MagentoFrameworkObjectManagerInterface
*/
protected $_objectManager;
/**
* @param MagentoFrameworkObjectManagerInterface $objectManager
*/
public function __construct(MagentoFrameworkObjectManagerInterface $objectManager)
$this->_objectManager = $objectManager;
/**
* Get captcha instance
*
* @param string $captchaType
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
* @throws InvalidArgumentException
*/
public function create()
$instance = $this->_objectManager->create('YourModuleModelCaptcha', ['formId' => 'event_subscriber']);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
'YourModuleModelCaptcha does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
and finally your model to overide the is required param in
YourModuleModelCaptcha:
<?php
namespace YourModuleModel;
class Captcha extends MagentoCaptchaModelDefaultModel
public function isRequired($login = null)
return true;
add a comment |
For those of you that cannot get this to work you may need to do what I did:
The reason you captcha may not be displaying is because the base settings are to use the Default captcha block which in the _toHtml does a check to see if the captcha is required.
If you have you settings for captcha to always show than you probably did not run into this issue however if it is not set to always show captchas and you do not want to always show captchas (ie account create/ login etc) than you need to set the logic for only your custom captcha to "Always be required".
on line 69 of vendor/magento/module-captcha/Block/Captcha/DefaultCaptcha.php you will see:
/**
* Renders captcha HTML (if required)
*
* @return string
*/
protected function _toHtml()
if ($this->getCaptchaModel()->isRequired())
$this->getCaptchaModel()->generate();
return parent::_toHtml();
return '';
$this->getCaptchaModel() calls $this->_captchaData->getCaptcha() which is in
vendor/magento/module-captcha/Helper/Data.php
/**
* Get Captcha
*
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
*/
public function getCaptcha($formId)
if (!array_key_exists($formId, $this->_captcha))
$captchaType = ucfirst($this->getConfig('type'));
if (!$captchaType)
$captchaType = self::DEFAULT_CAPTCHA_TYPE;
elseif ($captchaType == 'Default')
$captchaType = $captchaType . 'Model';
$this->_captcha[$formId] = $this->_factory->create($captchaType, $formId);
return $this->_captcha[$formId];
Here the getCaptcha method checks the config value for the type of captcha to render and loads its factory in with $this->_factory->create()
However stepping into this factory class you will see
public function create($captchaType, $formId)
$className = 'MagentoCaptchaModel\' . ucfirst($captchaType);
$instance = $this->_objectManager->create($className, ['formId' => $formId]);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
$className . ' does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
The issue here is that no matter what the factory will look in the Magento Captcha module for any Factory model.. so
We need to create a plugin to wrap around the helper and check for our form key and if it is our form key being used we need to create a new factory class that loads our model that extends MagentoCaptchaModelDefaultModel and overides the isRequired() method. Something that looks like this:
in YourModuleetcdi.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!--Custom Captcha-->
<type name="MagentoCaptchaHelperData">
<plugin name="custom-captcha" type="YourModulePluginHelperCaptchaData" />
</type>
in YourModulePluginHelperCaptchaData
<?php
namespace YourModulePluginHelper;
class CaptchaData
protected $_captcha = [];
public function __construct(
YourModuleModelCaptchaFactory $captchaFactory
)
$this->captchaFactory = $captchaFactory;
/**
* @param MagentoCaptchaHelperData $subject
* @param Closure $proceed
* @param $formId
* @return mixed
*/
public function aroundGetCaptcha(MagentoCaptchaHelperData $subject, Closure $proceed, $formId)
if ($formId == 'your_form_key')
$this->_captcha[$formId] = $this->captchaFactory->create();
return $this->_captcha[$formId];
return $proceed($formId);
in YourModuleModelCaptchaFactory
<?php
/**
* Captcha model factory
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace YourModuleModel;
class CaptchaFactory
/**
* @var MagentoFrameworkObjectManagerInterface
*/
protected $_objectManager;
/**
* @param MagentoFrameworkObjectManagerInterface $objectManager
*/
public function __construct(MagentoFrameworkObjectManagerInterface $objectManager)
$this->_objectManager = $objectManager;
/**
* Get captcha instance
*
* @param string $captchaType
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
* @throws InvalidArgumentException
*/
public function create()
$instance = $this->_objectManager->create('YourModuleModelCaptcha', ['formId' => 'event_subscriber']);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
'YourModuleModelCaptcha does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
and finally your model to overide the is required param in
YourModuleModelCaptcha:
<?php
namespace YourModuleModel;
class Captcha extends MagentoCaptchaModelDefaultModel
public function isRequired($login = null)
return true;
For those of you that cannot get this to work you may need to do what I did:
The reason you captcha may not be displaying is because the base settings are to use the Default captcha block which in the _toHtml does a check to see if the captcha is required.
If you have you settings for captcha to always show than you probably did not run into this issue however if it is not set to always show captchas and you do not want to always show captchas (ie account create/ login etc) than you need to set the logic for only your custom captcha to "Always be required".
on line 69 of vendor/magento/module-captcha/Block/Captcha/DefaultCaptcha.php you will see:
/**
* Renders captcha HTML (if required)
*
* @return string
*/
protected function _toHtml()
if ($this->getCaptchaModel()->isRequired())
$this->getCaptchaModel()->generate();
return parent::_toHtml();
return '';
$this->getCaptchaModel() calls $this->_captchaData->getCaptcha() which is in
vendor/magento/module-captcha/Helper/Data.php
/**
* Get Captcha
*
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
*/
public function getCaptcha($formId)
if (!array_key_exists($formId, $this->_captcha))
$captchaType = ucfirst($this->getConfig('type'));
if (!$captchaType)
$captchaType = self::DEFAULT_CAPTCHA_TYPE;
elseif ($captchaType == 'Default')
$captchaType = $captchaType . 'Model';
$this->_captcha[$formId] = $this->_factory->create($captchaType, $formId);
return $this->_captcha[$formId];
Here the getCaptcha method checks the config value for the type of captcha to render and loads its factory in with $this->_factory->create()
However stepping into this factory class you will see
public function create($captchaType, $formId)
$className = 'MagentoCaptchaModel\' . ucfirst($captchaType);
$instance = $this->_objectManager->create($className, ['formId' => $formId]);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
$className . ' does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
The issue here is that no matter what the factory will look in the Magento Captcha module for any Factory model.. so
We need to create a plugin to wrap around the helper and check for our form key and if it is our form key being used we need to create a new factory class that loads our model that extends MagentoCaptchaModelDefaultModel and overides the isRequired() method. Something that looks like this:
in YourModuleetcdi.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!--Custom Captcha-->
<type name="MagentoCaptchaHelperData">
<plugin name="custom-captcha" type="YourModulePluginHelperCaptchaData" />
</type>
in YourModulePluginHelperCaptchaData
<?php
namespace YourModulePluginHelper;
class CaptchaData
protected $_captcha = [];
public function __construct(
YourModuleModelCaptchaFactory $captchaFactory
)
$this->captchaFactory = $captchaFactory;
/**
* @param MagentoCaptchaHelperData $subject
* @param Closure $proceed
* @param $formId
* @return mixed
*/
public function aroundGetCaptcha(MagentoCaptchaHelperData $subject, Closure $proceed, $formId)
if ($formId == 'your_form_key')
$this->_captcha[$formId] = $this->captchaFactory->create();
return $this->_captcha[$formId];
return $proceed($formId);
in YourModuleModelCaptchaFactory
<?php
/**
* Captcha model factory
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace YourModuleModel;
class CaptchaFactory
/**
* @var MagentoFrameworkObjectManagerInterface
*/
protected $_objectManager;
/**
* @param MagentoFrameworkObjectManagerInterface $objectManager
*/
public function __construct(MagentoFrameworkObjectManagerInterface $objectManager)
$this->_objectManager = $objectManager;
/**
* Get captcha instance
*
* @param string $captchaType
* @param string $formId
* @return MagentoCaptchaModelCaptchaInterface
* @throws InvalidArgumentException
*/
public function create()
$instance = $this->_objectManager->create('YourModuleModelCaptcha', ['formId' => 'event_subscriber']);
if (!$instance instanceof MagentoCaptchaModelCaptchaInterface)
throw new InvalidArgumentException(
'YourModuleModelCaptcha does not implement MagentoCaptchaModelCaptchaInterface'
);
return $instance;
and finally your model to overide the is required param in
YourModuleModelCaptcha:
<?php
namespace YourModuleModel;
class Captcha extends MagentoCaptchaModelDefaultModel
public function isRequired($login = null)
return true;
answered 8 mins ago
DOfficialDOfficial
417
417
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f133238%2fmagento-2-how-to-add-captcha-to-a-custom-form%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown