How to override default contact form Model file in Magento 2.2.5?
-
22-02-2021 - |
Question
I want to override default contact form Model file (ie, Mail.php and mailinterface.php) in Magento 2.
Struggling to override this file since the last 2days.
Any help would be appreciated.
/var/www/html/magento/app/code/Amy/Contactform/Model/Mail.php
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Amy\Contactform\Model;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Area;
class Mail extends MailInterface
{
/**
* @var ConfigInterface
*/
private $contactsConfig;
/**
* @var TransportBuilder
*/
private $transportBuilder;
/**
* @var StateInterface
*/
private $inlineTranslation;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* Initialize dependencies.
*
* @param ConfigInterface $contactsConfig
* @param TransportBuilder $transportBuilder
* @param StateInterface $inlineTranslation
* @param StoreManagerInterface|null $storeManager
*/
public function __construct(
ConfigInterface $contactsConfig,
TransportBuilder $transportBuilder,
StateInterface $inlineTranslation,
StoreManagerInterface $storeManager = null
) {
$this->contactsConfig = $contactsConfig;
$this->transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->storeManager = $storeManager ?: ObjectManager::getInstance()->get(StoreManagerInterface::class);
}
/**
* Send email from contact form
*
* @param string $replyTo
* @param array $variables
* @return void
*/
public function send($recipient, $replyTo, array $variables)
{
/** @see \Magento\Contact\Controller\Index\Post::validatedParams() */
$replyToName = !empty($variables['data']['name']) ? $variables['data']['name'] : null;
if ($recipient == 'General feedback'){
$emails = ['aaa@gmail.com']; // add your email list
}else if ($recipient == 'Warranty'){
$emails = ['bbb@gmail.com']; // add your email list
}
$this->inlineTranslation->suspend();
try {
$transport = $this->transportBuilder
->setTemplateIdentifier($this->contactsConfig->emailTemplate())
->setTemplateOptions(
[
'area' => Area::AREA_FRONTEND,
'store' => $this->storeManager->getStore()->getId()
]
)
->setTemplateVars($variables)
->setFrom($this->contactsConfig->emailSender())
->addTo($emails)
->setReplyTo($replyTo, $replyToName)
->getTransport();
$transport->sendMessage();
} finally {
$this->inlineTranslation->resume();
}
}
}
/var/www/html/magento/app/code/Amy/Contactform/Model/Mail1Interface.php
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Amy\Contactform\Model;
/**
* Email from contact form
*
* @api
* @since 100.2.0
*/
interface Mail1Interface extends MialInterface
{
/**
* Send email from contact form
*
* @param string $replyTo Reply-to email address
* @param array $variables Email template variables
* @return void
* @since 100.2.0
*/
public function send($recipient, $replyTo, array $variables);
}
/var/www/html/magento/app/code/Amy/Contactform/Controller/Index/Post.php
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Amy\Contactform\Controller\Index;
use Magento\Contact\Model\ConfigInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Action\Context;
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;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;
class Post extends \Magento\Contact\Controller\Index\Post
{
/**
* @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
*/
public function __construct(
Context $context,
ConfigInterface $contactsConfig,
MailInterface $mail,
DataPersistorInterface $dataPersistor,
LoggerInterface $logger = null
) {
parent::__construct($context, $contactsConfig, $mail, $dataPersistor);
$this->context = $context;
$this->mail = $mail;
$this->dataPersistor = $dataPersistor;
$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());
$this->messageManager->addSuccessMessage(
__('Thanks for contacting us. Your inquiry was submitted and will be responded to you as soon as possible.')
);
$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['subject'],
$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('lastname')) === '') {
throw new LocalizedException(__('LastName is missing'));
}
if (trim($request->getParam('address1')) === '') {
throw new LocalizedException(__('Address1 is missing'));
}
if (trim($request->getParam('address2')) === '') {
throw new LocalizedException(__('Address2 is missing'));
}
if (trim($request->getParam('city')) === '') {
throw new LocalizedException(__('City is missing'));
}
if (trim($request->getParam('stateprovince')) === '') {
throw new LocalizedException(__('State is missing'));
}
if (trim($request->getParam('zipcode')) === '') {
throw new LocalizedException(__('Zipcode is missing'));
}
if (trim($request->getParam('subject')) === '') {
throw new LocalizedException(__('Subject 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();
}
}
/var/www/html/magento/app/code/Amy/Contactform/etc/di.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Contact\Block\ContactForm" type="Amy\Contactform\Block\ContactForm" />
<preference for="Magento\Contact\Controller\Index\Post" type="Amy\Contactform\Controller\Index\Post" />
<preference for="Magento\Contact\Model\Mail" type="Amy\Contactform\Model\Mail" />
</config>
Solution 2
After struggling for days, I got the solution This is how you will be able to override the contact Model Mail.php file, I posted this answer, because it may be useful to others.
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Amy\Contactform\Model;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Area;
use Magento\Contact\Model\ConfigInterface;
class Mail extends \Magento\Contact\Model\Mail implements \Magento\Contact\Model\MailInterface
{
/**
* @var ConfigInterface
*/
private $contactsConfig;
/**
* @var TransportBuilder
*/
private $transportBuilder;
/**
* @var StateInterface
*/
private $inlineTranslation;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* Initialize dependencies.
*
* @param ConfigInterface $contactsConfig
* @param TransportBuilder $transportBuilder
* @param StateInterface $inlineTranslation
* @param StoreManagerInterface|null $storeManager
*/
public function __construct(
ConfigInterface $contactsConfig,
TransportBuilder $transportBuilder,
StateInterface $inlineTranslation,
StoreManagerInterface $storeManager = null
) {
$this->contactsConfig = $contactsConfig;
$this->transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->storeManager = $storeManager ?: ObjectManager::getInstance()->get(StoreManagerInterface::class);
}
/**
* Send email from contact form
*
* @param string $replyTo
* @param array $variables
* @return void
*/
public function send($recipient, $replyTo, array $variables)
{
/** @see \Magento\Contact\Controller\Index\Post::validatedParams() */
$replyToName = !empty($variables['data']['name']) ? $variables['data']['name'] : null;
if ($recipient == 'General feedback'){
$emails = ['aaa@gmail.com']; // add your email list
}else if ($recipient == 'Warranty'){
$emails = ['bbb@gmail.com']; // add your email list
}
$this->inlineTranslation->suspend();
try {
$transport = $this->transportBuilder
->setTemplateIdentifier($this->contactsConfig->emailTemplate())
->setTemplateOptions(
[
'area' => Area::AREA_FRONTEND,
'store' => $this->storeManager->getStore()->getId()
]
)
->setTemplateVars($variables)
->setFrom($this->contactsConfig->emailSender())
->addTo($emails)
->setReplyTo($replyTo, $replyToName)
->getTransport();
$transport->sendMessage();
} finally {
$this->inlineTranslation->resume();
}
}
}
OTHER TIPS
Have you tried the preference as below :
<?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\Model\Mail" type="VendorName\ModuleName\Model\Mail" />
</config>
Mailinterface.php model is an interface class and we can't directly override magento's core interfaces. You can override Mail.php using preference like :
<preference for="Magento\Contact\Model\Mail" type="Namespace\Modulename\Model\MailOverride"/>
Thanks