0

I am struggling with adding captcha in few forms, have gone through its module I find it really intresting but not getting clear idea ! If anyone is having clear concept please describe . thanks!

4

It's long answer though.

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>
                    <product_review_form>1</product_review_form>
                </shown_to_logged_in_user>
                <always_for>
                    <product_review_form>1</product_review_form>
                </always_for>
            </captcha>
        </customer>
        <captcha translate="label">
            <frontend>
                <areas>
                    <product_review_form>
                        <label>Product Review Form</label>
                    </product_review_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 'Product Review Form'

Step 3: Create Vendor/Module/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="product.review.form">
                <action method="setTemplate">
                    <argument name="template" xsi:type="string">Vendor_Module::review/form.phtml</argument>
                </action>
                <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">product_review_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>
            </referenceBlock>
            <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/Moduel/view/frontend/templates/review/form.phtml

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/**
 * @var $block \Magento\Review\Block\Form
 */
?>
<div class="block review-add">
    <div class="block-title"><strong><?php /* @escapeNotVerified */ echo __('Write Your Own Review') ?></strong></div>
<div class="block-content">
<?php if ($block->getAllowWriteReviewFlag()): ?>
<form action="<?php /* @escapeNotVerified */ echo $block->getAction() ?>" class="review-form" method="post" id="review-form" data-role="product-review-form" data-bind="scope: 'review-form'">
    <?php echo $block->getBlockHtml('formkey'); ?>
    <?php echo $block->getChildHtml('form_fields_before')?>
    <fieldset class="fieldset review-fieldset" data-hasrequired="<?php __('* Required Fields'); ?>">
        <legend class="legend review-legend"><span><?php /* @escapeNotVerified */ echo __("You're reviewing:"); ?></span><strong><?php echo $block->escapeHtml($block->getProductInfo()->getName()) ?></strong></legend><br />
        <?php if ($block->getRatings() &amp;&amp; $block->getRatings()->getSize()): ?>
        <span id="input-message-box"></span>
        <fieldset class="field required review-field-ratings">
            <legend class="label"><span><?php /* @escapeNotVerified */ echo __('Your Rating') ?><span></legend><br/>
            <div class="control">
                <div class="nested" id="product-review-table">
                    <?php foreach ($block->getRatings() as $_rating): ?>
                        <div class="field choice review-field-rating">
                            <label class="label" id="<?php echo $block->escapeHtml($_rating->getRatingCode()) ?>_rating_label"><span><?php echo $block->escapeHtml($_rating->getRatingCode()) ?></span></label>
                            <div class="control review-control-vote">
                            <?php $options = $_rating->getOptions();?>
                            <?php $iterator = 1; foreach ($options as $_option): ?>
                                <input
                                    type="radio"
                                    name="ratings[<?php /* @escapeNotVerified */ echo $_rating->getId() ?>]"
                                    id="<?php echo $block->escapeHtml($_rating->getRatingCode()) ?>_<?php /* @escapeNotVerified */ echo $_option->getValue() ?>"
                                    value="<?php /* @escapeNotVerified */ echo $_option->getId() ?>"
                                    class="radio"
                                    data-validate="{required:true, messages:{required:'Please select one of each of the ratings above.'}}"
                                    aria-labelledby="<?php echo $block->escapeHtml($_rating->getRatingCode()) ?>_rating_label <?php echo $block->escapeHtml($_rating->getRatingCode()) ?>_<?php /* @escapeNotVerified */ echo $_option->getValue() ?>_label" />
                                <label
                                    class="rating-<?php /* @escapeNotVerified */ echo $iterator; ?>"
                                    for="<?php echo $block->escapeHtml($_rating->getRatingCode()) ?>_<?php /* @escapeNotVerified */ echo $_option->getValue() ?>"
                                    title="<?php /* @escapeNotVerified */ echo __('%1 %2', $iterator, $iterator > 1 ? 'stars' : 'star') ?>"
                                    id="<?php echo $block->escapeHtml($_rating->getRatingCode()) ?>_<?php /* @escapeNotVerified */ echo $_option->getValue() ?>_label">
                                    <span><?php /* @escapeNotVerified */ echo __('%1 %2', $iterator, $iterator > 1 ? 'stars' : 'star') ?></span>
                                </label>
                            <?php $iterator++; ?>
                            <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <input type="hidden" name="validate_rating" class="validate-rating" value="" />
            </div>
        </fieldset>
    <?php endif ?>
        <div class="field review-field-nickname required">
            <label for="nickname_field" class="label"><span><?php /* @escapeNotVerified */ echo __('Nickname') ?></span></label>
            <div class="control">
                <input type="text" name="nickname" id="nickname_field" class="input-text" data-validate="{required:true}" data-bind="value: nickname()" />
            </div>
        </div>
        <div class="field review-field-summary required">
            <label for="summary_field" class="label"><span><?php /* @escapeNotVerified */ echo __('Summary') ?></span></label>
            <div class="control">
                <input type="text" name="title" id="summary_field" class="input-text" data-validate="{required:true}" data-bind="value: review().title" />
            </div>
        </div>
        <div class="field review-field-text required">
            <label for="review_field" class="label"><span><?php /* @escapeNotVerified */ echo __('Review') ?></span></label>
            <div class="control">
                <textarea name="detail" id="review_field" cols="5" rows="3" data-validate="{required:true}" data-bind="value: review().detail"></textarea>
            </div>
        </div>
        <?php echo $block->getChildHtml('form.additional.info'); ?>
    </fieldset>
    <div class="actions-toolbar review-form-actions">
        <div class="primary actions-primary">
            <button type="submit" class="action submit primary"><span><?php /* @escapeNotVerified */ echo __('Submit Review') ?></span></button>
        </div>
    </div>
</form>
<script type="text/x-magento-init">
{
    "#review-form": {
        "Magento_Review/js/error-placement": {}
    }
}
</script>
<?php else: ?>
    <div class="message info notlogged" id="review-form">
        <div>
            <?php /* @escapeNotVerified */ echo __('Only registered users can write reviews. Please <a href="%1">Sign in</a> or <a href="%2">create an account</a>', $block->getLoginLink(), $block->getRegisterUrl()) ?>
        </div>
    </div>
<?php endif ?>
</div>
</div>

Step 5: 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_review_product_post">
        <observer name="captcha_product_review_form" instance="Vendor\Module\Observer\CheckProductReviewFormObserver" />
    </event>
</config>

Step 6: Vendor/Module/Observer/CheckProductReviewFormObserver.php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Captcha\Observer\CaptchaStringResolver;

class CheckProductReviewFormObserver implements ObserverInterface
{
    /**
     * @var \Magento\Captcha\Helper\Data
     */
    protected $_helper;

    /**
     * @var \Magento\Framework\App\ActionFlag
     */
    protected $_actionFlag;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var \Magento\Framework\App\Response\RedirectInterface
     */
    protected $redirect;

    /**
     * @var CaptchaStringResolver
     */
    protected $captchaStringResolver;

    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * @param \Magento\Captcha\Helper\Data $helper
     * @param \Magento\Framework\App\ActionFlag $actionFlag
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     * @param \Magento\Framework\App\Response\RedirectInterface $redirect
     * @param CaptchaStringResolver $captchaStringResolver
     */
    public function __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;
    }

    /**
     * Check CAPTCHA on review Form
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $formId = 'product_review_form';
        $captcha = $this->_helper->getCaptcha($formId);
        if ($captcha->isRequired()) {
            /** @var \Magento\Framework\App\Action\Action $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('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
                $this->redirect->redirect($controller->getResponse(), $this->redirect->getRefererUrl());
            }
        }
    }

    /**
     * Get Data Persistor
     *
     * @return DataPersistorInterface
     */
    private function getDataPersistor()
    {
        if ($this->dataPersistor === null) {
            $this->dataPersistor = ObjectManager::getInstance()
                ->get(DataPersistorInterface::class);
        }

        return $this->dataPersistor;
    }
}

Clear magento cache.

  • complete review form is blank means there is no form now!! – supriya mishra Jan 12 '17 at 9:57
  • You follow every step? – Sohel Rana Jan 12 '17 at 9:58
  • yes Completely !! – supriya mishra Jan 12 '17 at 10:06
  • Do I need to change anything in my custom theme ?? – supriya mishra Jan 12 '17 at 10:13
  • Could you replace 'Vendor_Module' to 'YourVendor_YourModule' from catalog_product_view.xml – Sohel Rana Jan 12 '17 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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