0

I have override contact form post controller in custom module. It is calling from my module but i am getting error as

Fatal error: Uncaught Error: Call to a member function send()

private function sendEmail($post) {
    $this->mail->send($post['email'], ['data' => new \Magento\Framework\DataObject($post)]);
}

print_r($post);

$post is giving data

Vendor/Module/etc/frontend/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">
    <preference for="Magento\Contact\Controller\Index\Post" type="Vendor\Module\Controller\Index\Post" />
</config>

Vendor/Module/Controller/Post.php

<?php

namespace Vendor\Module\Controller\Index;

use Magento\Contact\Model\ConfigInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\PhpEnvironment\Request;
use Psr\Log\LoggerInterface;

class Post extends \Magento\Contact\Controller\Index {

private static $_siteVerifyUrl = "https://www.google.com/recaptcha/api/siteverify?";
private $_secret;
private static $_version = "php_1.0";

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

/**
 * @var Context
 */
private $context;

/**
 * @var MailInterface
 */
private $mail;

/**
 * @var LoggerInterface
 */
private $logger;

/**
 * @param Context $context
 * @param ConfigInterface $contactsConfig
 * @param MailInterface $mail
 * @param DataPersistorInterface $dataPersistor
 * @param LoggerInterface $logger
 */

/**
 * Post user question
 *
 * @return Redirect
 */
public function execute() {


    if (!$this->isPostRequest()) {
        return $this->resultRedirectFactory->create()->setPath('*/*/');
    }
    try {
        echo '<pre>';
        print_r($this->getRequest()->getPostValue());
        echo '</pre>';

        echo '<pre>';
        print_r($this->validatedParams());
        echo '</pre>';


        $captcha = $this->getRequest()->getParam('g-recaptcha-response');
        $secret = '6LfTaGIUAAAAANO90oUqqLs3oNt-qy6_9g2_eC5R';
        $response = null;
        $path = self::$_siteVerifyUrl;
        $dataC = array(
            'secret' => $secret,
            'remoteip' => $_SERVER["REMOTE_ADDR"],
            'v' => self::$_version,
            'response' => $captcha
        );
        $req = "";
        foreach ($dataC as $key => $value) {
            $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
        }
        $req = substr($req, 0, strlen($req) - 1);
        $response = file_get_contents($path . $req);
        $answers = json_decode($response, true);

        if (trim($answers ['success']) == true) {
            $this->sendEmail($this->validatedParams());
            $this->messageManager->addSuccess(
                    __('Thank you for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->getDataPersistor()->clear('contact_us');
        } else {
            $this->messageManager->addError(__('Invalid Recaptcha'));
        }
        $this->sendEmail($this->validatedParams());
        $this->messageManager->addSuccess(
                __('Thank you for contacting us with your comments and questions. We\'ll respond to you very soon.')
        );
        $this->getDataPersistor()->clear('contact_us');
    } catch (LocalizedException $e) {
        $this->messageManager->addErrorMessage($e->getMessage());
        $this->getDataPersistor()->set('contact_us', $this->getRequest()->getParams());
    } catch (\Exception $e) {
        $this->logger->critical($e);
        $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
        );
        $this->getDataPersistor()->set('contact_us', $this->getRequest()->getParams());
    }
    return $this->resultRedirectFactory->create()->setPath('contact/index');
}

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

    return $this->dataPersistor;
}

/**
 * @param array $post Post data from contact form
 * @return void
 */
private function sendEmail($post) {
    print_r($post);
    $this->mail->send($post['email'], ['data' => new \Magento\Framework\DataObject($post)]);
}

/**
 * @return bool
 */
private function isPostRequest() {
    /** @var Request $request */
    $request = $this->getRequest();
    return !empty($request->getPostValue());
}

/**
 * @return array
 * @throws \Exception
 */
private function validatedParams() {
    $request = $this->getRequest();
    if (trim($request->getParam('name')) === '') {
        throw new LocalizedException(__('Name is missing'));
    }
    if (trim($request->getParam('comment')) === '') {
        throw new LocalizedException(__('Comment is missing'));
    }
    if (false === \strpos($request->getParam('email'), '@')) {
        throw new LocalizedException(__('Invalid email address'));
    }
    if (trim($request->getParam('hideit')) !== '') {
        throw new \Exception();
    }

    return $request->getParams();
}

}

1 Answer 1

0

First, change the line:

class Post extends \Magento\Contact\Controller\Index

to

class Post extends \Magento\Contact\Controller\Post

If still, the problem exists, please post the outcome.

Update: Please put the __construct() in the class:

public function __construct(
    Context $context,
    ConfigInterface $contactsConfig,
    MailInterface $mail,
    DataPersistorInterface $dataPersistor,
    LoggerInterface $logger = null
) {
       parent::__construct($context, $contactsConfig);
       $this->context = $context;
       $this->mail = $mail;
       $this->dataPersistor = $dataPersistor;
       $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
   }

In the __construct(), we have used object of Magento\Contact\Model\MailInterface class and initialized $this->mail with this object.

I hope it should solve your problem.

6
  • 1
    Thanks for correction but it should be class Post extends \Magento\Contact\Controller\Index\Post
    – Magecode
    Commented Jul 5, 2018 at 13:13
  • Still same problem exist
    – Magecode
    Commented Jul 5, 2018 at 13:13
  • @Magecode, please check the update section. Commented Jul 5, 2018 at 13:21
  • parent::__construct($context, $contactsConfig,$mail, $dataPersistor);
    – Magecode
    Commented Jul 5, 2018 at 13:31
  • But still same issiue
    – Magecode
    Commented Jul 5, 2018 at 13:31

Your Answer

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

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