Risposte:
È necessario seguire alcuni passaggi per utilizzare magento captcha nel modulo personalizzato.
Passo 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>
<Clienti>
<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>
</ Cliente>
<captcha translate = "label">
<Frontend>
<zone>
<Custom_form>
<label> Modulo personalizzato </label>
</ Custom_form>
</ Aree>
</ Frontend>
</ Captcha>
</ Default>
</ Config>
Passaggio 2: vai su " Ammin. -> Negozi -> Configurazione -> Cliente -> Configurazione cliente -> Captcha " e configura. Puoi vedere il nuovo valore dei moduli 'Modulo personalizzato'
Passaggio 3: creare 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 = "urna: magento: framework: View / Layout / etc / page_configuration.xsd">
<Head>
<title> Modulo personalizzato </title>
</ Head>
<Body>
<referenceContainer name = "content">
<block class = "Vendor \ Module \ Block \ CaptchaForm" name = "contactForm" template = "Vendor_Module :: captchaform.phtml">
<container name = "form.additional.info" label = "Informazioni aggiuntive modulo">
<block class = "Magento \ Captcha \ Block \ Captcha" name = "captcha" after = "-" cacheable = "false">
<action method = "setFormId">
<argomento name = "formId" xsi: type = "string"> custom_form </argument>
</ Action>
<action method = "setImgWidth">
<argomento name = "width" xsi: type = "string"> 230 </argument>
</ Action>
<action method = "setImgHeight">
<argomento name = "width" xsi: type = "string"> 50 </argument>
</ Action>
</ Block>
</ Container>
</ Block>
</ ReferenceContainer>
<referenceBlock name = "head.components">
<block class = "Magento \ Framework \ View \ Element \ Js \ Components" name = "captcha_page_head_components" template = "Magento_Captcha :: js / components.phtml" />
</ ReferenceBlock>
</ Body>
</ Page>
Step 4: Vendor/Module/Block/CaptchaForm.php
namespace Vendor \ Module \ Block;
classe CaptchaForm estende \ Magento \ Framework \ View \ Element \ Template
{
funzione pubblica getFormAction ()
{
return $ this-> getUrl ('yourroute / index / post', ['_secure' => true]);
}
}
Passaggio 5: Vendor/Moduel/view/frontend/templates/captchaform.phtml
<form class = "form contact"
action = "<? php / * @escapeNotVerified * / echo $ block-> getFormAction ();?>"
id = "modulo di contatto"
method = "post"
data-hasrequired = "<? php / * @escapeNotVerified * / echo __ ('* Campi obbligatori')?>"
Dati-mago-init = '{ "convalida": {}}'>
<fieldset class = "fieldset">
<legend class = "legend"> <span> <? php / * @escapeNotVerified * / echo __ ('Scrivici')?> </span> </legend> <br />
<div class = "nome campo richiesto">
<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" dati-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 = "{richiesto: vero, 'validate-email': vero}" />
</ 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>
<Tasto />
</ Div>
</ Div>
</ Form>
Ora puoi vedere captcha nel tuo modulo. Ora è necessario convalidare il captcha usando l'osservatore. Quindi utilizzo l'evento predispatch post controller per la convalida.
Passaggio 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">
<nome evento = "controller_action_predispatch_yourroute_index_post">
<nome osservatore = "captcha_custom_form" istanza = "Venditore \ Modulo \ Osservatore \ CheckCustomFormObserver" />
</ Event>
</ Config>
Passaggio 7: Vendor/Module/Observer/CheckCustomFormObserver.php
namespace Vendor \ Module \ Observer;
usa Magento \ Framework \ Event \ ObserverInterface;
usa Magento \ Framework \ App \ Request \ DataPersistorInterface;
usa Magento \ Framework \ App \ ObjectManager;
usa Magento \ Captcha \ Observer \ CaptchaStringResolver;
la classe CheckCustomFormObserver implementa ObserverInterface
{
/ **
* @var \ Magento \ Captcha \ Helper \ Data
* /
$ _helper protetto;
/ **
* @var \ Magento \ Framework \ App \ ActionFlag
* /
$_actionFlag protetto;
/ **
* @var \ Magento \ Framework \ Message \ ManagerInterface
* /
protetto $ messageManager;
/ **
* @var \ Magento \ Framework \ App \ Response \ RedirectInterface
* /
$ redirect protetto;
/ **
* @var CaptchaStringResolver
* /
protetto $ captchaStringResolver;
/ **
* @var DataPersistorInterface
* /
private $ dataPersistor;
/ **
* Helper @param \ Magento \ Captcha \ Helper \ Data $
* @param \ Magento \ Framework \ App \ ActionFlag $ actionFlag
* @param \ Magento \ Framework \ Message \ ManagerInterface $ messageManager
* @param \ Magento \ Framework \ App \ Response \ RedirectInterface $ redirect
* @param CaptchaStringResolver $ captchaStringResolver
* /
funzione pubblica __construct (
\ Magento \ Captcha \ Helper \ Data $ helper,
\ Magento \ Framework \ App \ ActionFlag $ actionFlag,
\ Magento \ Framework \ Message \ ManagerInterface $ messageManager,
\ Magento \ Framework \ App \ Response \ RedirectInterface $ redirect,
CaptchaStringResolver $ captchaStringResolver
) {
$ this -> _ helper = $ helper;
$ this -> _ actionFlag = $ actionFlag;
$ this-> messageManager = $ messageManager;
$ this-> redirect = $ redirect;
$ this-> captchaStringResolver = $ captchaStringResolver;
}
/ **
* Controlla CAPTCHA sul modulo personalizzato
*
* @param \ Magento \ Framework \ Event \ Observer $ observer
* @return void
* /
funzione pubblica execute (\ Magento \ Framework \ Event \ Observer $ observer)
{
$ formId = 'custom_form';
$ captcha = $ this -> _ helper-> getCaptcha ($ formId);
if ($ captcha-> isRequired ()) {
/ ** @var \ Magento \ Framework \ App \ Action \ Action $ controller * /
$ controller = $ observer-> getControllerAction ();
if (! $ captcha-> isCorrect ($ this-> captchaStringResolver-> solving ($ controller-> getRequest (), $ formId))) {
$ this-> messageManager-> addError (__ ('CAPTCHA errato.'));
$ this-> getDataPersistor () -> set ($ formId, $ controller-> getRequest () -> getPostValue ());
$ this -> _ actionFlag-> set ('', \ Magento \ Framework \ App \ Action \ Action :: FLAG_NO_DISPATCH, true);
$ this-> redirect-> redirect ($ controller-> getResponse (), 'percorso / indice / indice');
}
}
}
/ **
* Ottieni dati Persistor
*
* @return DataPersistorInterface
* /
funzione privata getDataPersistor ()
{
if ($ this-> dataPersistor === null) {
$ this-> dataPersistor = ObjectManager :: getInstance ()
-> get (DataPersistorInterface :: classe);
}
restituisce $ this-> dataPersistor;
}
}
Per quelli di voi che non riescono a farlo funzionare, potrebbe essere necessario fare ciò che ho fatto:
Il motivo per cui captcha potrebbe non essere visualizzato è perché le impostazioni di base devono utilizzare il blocco captcha predefinito che in _toHtml verifica se il captcha è necessario.
Se hai le impostazioni per captcha da mostrare sempre di quanto probabilmente non hai riscontrato questo problema, tuttavia se non è impostato per mostrare sempre captcha e non vuoi mostrare sempre captcha (ad esempio, creazione / accesso dell'account, ecc.) Di quanto sia necessario imposta la logica solo per il tuo captcha personalizzato su "Sempre richiesto".
alla riga 69 del fornitore / magento / module-captcha / Block / Captcha / DefaultCaptcha.php vedrai:
/**
* Renders captcha HTML (if required)
*
* @return string
*/
protected function _toHtml()
{
if ($this->getCaptchaModel()->isRequired()) {
$this->getCaptchaModel()->generate();
return parent::_toHtml();
}
return '';
}
$this->getCaptchaModel()chiamate $this->_captchaData->getCaptcha()che si trovano in
vendor / magento / module-captcha / Helper / Data.php
/**
* Get Captcha
*
* @param string $formId
* @return \Magento\Captcha\Model\CaptchaInterface
*/
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];
}
Qui il metodo getCaptcha controlla il valore di configurazione per il tipo di captcha per il rendering e carica la sua factory con $this->_factory->create()
Comunque entrerai in questa classe di fabbrica che vedrai
public function create($captchaType, $formId)
{
$className = 'Magento\Captcha\Model\\' . ucfirst($captchaType);
$instance = $this->_objectManager->create($className, ['formId' => $formId]);
if (!$instance instanceof \Magento\Captcha\Model\CaptchaInterface) {
throw new \InvalidArgumentException(
$className . ' does not implement \Magento\Captcha\Model\CaptchaInterface'
);
}
return $instance;
}
Il problema qui è che non importa quale sarà la fabbrica nel modulo Captcha di Magento per qualsiasi modello di Fabbrica ... quindi
Dobbiamo creare un plug-in per avvolgere l'helper e verificare la chiave del nostro modulo e se è la nostra chiave del modulo in uso dobbiamo creare una nuova classe di fabbrica che carica il nostro modello che estende \ Magento \ Captcha \ Model \ DefaultModel e si sovrappone il metodo isRequired (). Qualcosa che assomiglia a questo:
in \ Your \ Module \ etc \ di.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="\Magento\Captcha\Helper\Data">
<plugin name="custom-captcha" type="Your\Module\Plugin\Helper\CaptchaData" />
</type>
in Your \ Module \ Plugin \ Helper \ CaptchaData
<?php
namespace Your\Module\Plugin\Helper;
class CaptchaData
{
protected $_captcha = [];
public function __construct(
\Your\Module\Model\CaptchaFactory $captchaFactory
) {
$this->captchaFactory = $captchaFactory;
}
/**
* @param \Magento\Captcha\Helper\Data $subject
* @param \Closure $proceed
* @param $formId
* @return mixed
*/
public function aroundGetCaptcha(\Magento\Captcha\Helper\Data $subject, \Closure $proceed, $formId)
{
if ($formId == 'your_form_key') {
$this->_captcha[$formId] = $this->captchaFactory->create();
return $this->_captcha[$formId];
}
return $proceed($formId);
}
}
in \ Your \ Module \ Model \ CaptchaFactory
<?php
/**
* Captcha model factory
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Your\Module\Model;
class CaptchaFactory
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $_objectManager;
/**
* @param \Magento\Framework\ObjectManagerInterface $objectManager
*/
public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager)
{
$this->_objectManager = $objectManager;
}
/**
* Get captcha instance
*
* @param string $captchaType
* @param string $formId
* @return \Magento\Captcha\Model\CaptchaInterface
* @throws \InvalidArgumentException
*/
public function create()
{
$instance = $this->_objectManager->create('Your\Module\Model\Captcha', ['formId' => 'event_subscriber']);
if (!$instance instanceof \Magento\Captcha\Model\CaptchaInterface) {
throw new \InvalidArgumentException(
'Your\Module\Model\Captcha does not implement \Magento\Captcha\Model\CaptchaInterface'
);
}
return $instance;
}
}
e infine il tuo modello per sostituire il parametro richiesto in \ Your \ Module \ Model \ Captcha :
<?php
namespace Your\Module\Model;
class Captcha extends \Magento\Captcha\Model\DefaultModel
{
public function isRequired($login = null)
{
return true;
}
}
Ho bisogno di captcha nella pagina degli abbonati alla newsletter grazie a sohan sono stato usato osservatore della newsletter e captcha lavora nella pagina della newsletter per me.
1) app / codice / Vendorname / nome modulo / 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_newsletter>1</custom_newsletter>
</shown_to_logged_in_user>
<always_for>
<custom_newsletter>1</custom_newsletter>
</always_for>
</captcha>
</customer>
<captcha translate="label">
<frontend>
<areas>
<custom_newsletter>
<label>Newsletter Form</label>
</custom_newsletter>
</areas>
</frontend>
</captcha>
</default>
</config>
2) Vai a "Ammin. -> Negozi -> Configurazione -> Cliente -> Configurazione cliente -> Captcha" e configura. Puoi vedere i nuovi moduli valutare "Modulo newsletter".
3) copia il file di layout nel tema (default.xml)
<block class="Magento\Newsletter\Block\Subscribe" name="subscribe form " template="Magento_Newsletter::subscribe.phtml">
<container name="form.additional.info" label="Form Additional Info">
<block class="Magento\Captcha\Block\Captcha" name="captcha" after="-" cacheable="false">
<action method="setFormId">
<argument name="formId" xsi:type="string">custom_newsletter</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>
4) Crea osservatore -> crea il file event.xml in app / codice / Vendorname / nome modulo / etc / frontend
<?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_newsletter_subscriber_new">
<observer name="captcha_newletter_form" instance="Vendorname/Modulename/Observer\CheckCustomFormObserver" />
</event>
</config>
5) Crea un modello di osservatore e controlla l'app / codice captcha / Nome fornitore / Nome modulo / Observer / CheckCustomFormObserver.php
public function execute(\Magento\Framework\Event\Observer $observer)
{ $formId = 'custom_newsletter';
$captcha = $this->_helper->getCaptcha($formId);
if ($captcha->isRequired()) {
/** @var \Magento\Framework\App\Action\Action $controller */
$controller = $observer->getControllerAction();
$params=$controller->getRequest()->getPost();
$currentpage = $params['currentpage'];
if (!$captcha->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId))) {
$this->messageManager->addError(__('Incorrect CAPTCHA.'));
$this->getDataPersistor()->set($formId, $controller->getRequest()->getPostValue());
$this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
$this->redirect->redirect($controller->getResponse(), $currentpage);
}
}
}