0

I want to send welcome email when a checkbox is checked in contact form in Magento2.2.5?

Refer screenshot

enter image description here

Any help would be appreciated.

  • You can try calling controller via ajax after the specific checkbox checked and trigger and email from the controller @Amy – Prathap Gunasekaran Mar 18 '19 at 8:27
  • do you want to subscribe for newsletter while clicking on checkbox ? – Manashvi Birla Mar 18 '19 at 9:01
  • Yep, I want to subscribe for newsletter while clicking on checkbox. – Amy Mar 18 '19 at 9:26
  • Thanks Manashvi, will check your answer and let you know. – Amy Mar 18 '19 at 10:25
  • Hi Manashvi, I have checked your answer, But after submitting the form it shows blank page. – Amy Mar 18 '19 at 11:12
0

override the Magento\Contact\Controller\Index\Post to subscribe the user to newsletter.

app/code/Namespace/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">
    <preference for="Magento\Contact\Controller\Index\Post" type="Namespace\Module\Controller\Contact\Index\Post" />
</config>

app/code/Namespace/Module/Controller/Contact/Index/Post

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Namespace\Company\Controller\Contact\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\DataObject;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\PhpEnvironment\Request;
use Psr\Log\LoggerInterface;
use Magento\Newsletter\Model\SubscriberFactory;

class Post extends \Magento\Contact\Controller\Index {
    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

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

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

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

    /**
     * @var \Magento\Newsletter\Model\SubscriberFactory
     */
    protected $subscriberFactory;

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

    /**
     * Post user question
     *
     * @return Redirect
     */
    public function execute()
    {
        if (!$this->isPostRequest()) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
        try {
            $this->sendEmail($this->validatedParams());

            //  subscribe to newsletter
            if ($this->getRequest()->getParam('is_subscribed', false)) {
                $this->subscriberFactory->create()->subscribe($this->getRequest()->getParam('email'));
            }

            $this->messageManager->addSuccessMessage(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->dataPersistor->clear('contact_us');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            $this->dataPersistor->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->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        }
        return $this->resultRedirectFactory->create()->setPath('contact/index');
    }

    /**
     * @param array $post Post data from contact form
     * @return void
     */
    private function sendEmail($post) {
        $this->mail->send(
            $post['email'],
            ['data' => new 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();
    }
}

NOTE In the contact us form, keep the newsletter checkbox name as is_subscribed to get its value in the Post controller

| improve this answer | |
  • Hi How would you do that onchange check the checkbox and not clicking the button. As soon as the checkbox is checked onchange event will trigger and will send email accordingly. How can we pass ajax call to controller with speciifc fucntion carrying out that task of sending email? – J. Doe Jul 8 at 16:02
  • @J.Doe - plz add a new question for that, and share the link here. – Manashvi Birla Jul 9 at 6:45
  • magento.stackexchange.com/questions/316787/… Thanks for your quick response @Manashvi Birla – J. Doe Jul 9 at 6:58

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.