At this,case you have to use around method (aroundExecute()
).
First, create di.xml
at app/code/{VendorName}/{Modulename}/etc/frontend/
for define plugin class.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Contact\Controller\Index\Post">
<plugin name="add_new_item" sortOrder="1" disabled="false"
type="StackExchange\Magentodemo\Plugin\ContactPostPlugin"/>
</type>
</config>
Now, you have to create a plugin where you have to check captcha is valid or not at app/code/{VendorName}/{Modulename}/Plugin/
<?php
namespace StackExchange\Magentodemo\Plugin;
class ContactPostPlugin {
/**
* @var \Magento\Framework\UrlInterface
*/
protected $urlInterface;
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
protected $messageManager;
public function __construct(
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Framework\UrlInterface $urlInterface
) {
$this->messageManager = $messageManager;
$this->urlInterface = $urlInterface;
}
public function aroundExecute(
\Magento\Contact\Controller\Index\Post $subject,
\Closure $proceed
)
{
if({CapctheIsNOtValdated}) // condition for not valdate captcha
{
$url = $this->urlInterface->getUrl('contact/index');
$this->messageManager->addErrorMessage('Captcha is not valid');
return $subject->getResponse()->setRedirect($url);
}
return $proceed();
}
}