2

I created a custom form and even extended the controller of Magento Contact Us and modified it. Now my problem is that whenever, I fill out the form that I created, It will use the email template of Magento Contact Us to send notification. Sorry I'm just new to this. I hope you can help me.

And also I have created a custom email template for my form under Marketing>Email Templates, I want this email template to be used in my custom form.

Attached is the current screenshot of my Index.php Controller.

enter image description here

Here is the code of Index.php Controller

    <?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Company\ModuleName\Controller;

use Magento\Framework\Exception\NotFoundException;
use Magento\Framework\App\RequestInterface;
use Magento\Store\Model\ScopeInterface;

/**
 * Contact index controller
 */
abstract class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * Recipient email config path
     */
    const XML_PATH_EMAIL_RECIPIENT = 'contact/email/recipient_email';

    /**
     * Sender email config path
     */
    const XML_PATH_EMAIL_SENDER = 'contact/email/sender_email_identity';

    /**
     * Email template config path
     */
    const XML_PATH_EMAIL_TEMPLATE = 'contact/email/email_template';

    /**
     * Enabled config path
     */
    const XML_PATH_ENABLED = 'contact/contact/enabled';

    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        parent::__construct($context);
        $this->_transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
    }

    /**
     * Dispatch request
     *
     * @param RequestInterface $request
     * @return \Magento\Framework\App\ResponseInterface
     * @throws \Magento\Framework\Exception\NotFoundException
     */
    public function dispatch(RequestInterface $request)
    {
        if (!$this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE)) {
            throw new NotFoundException(__('Page not found.'));
        }
        return parent::dispatch($request);
    }
}

And Here is the Controller

    <?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Company\ModuleName\Controller\Index;

use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;

class Cs extends  \Company\ModuleName\Controller\Index
{
    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * Post user question
     *
     * @return void
     * @throws \Exception
     */
    public function execute()
    {
        $post = $this->getRequest()->getPostValue();
        if (!$post) {
            $this->_redirect('*/*/');
            return;
        }

        $this->inlineTranslation->suspend();
        try {
            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($post);

            $error = false;

            if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['address']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['mix-name']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['company']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['city']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['address']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                $error = true;
            }
             if (!\Zend_Validate::is(trim($post['telephone']), 'NotEmpty')) {
                $error = true;
            }
             if (!\Zend_Validate::is(trim($post['zip']), 'NotEmpty')) {
                $error = true;
            }
             if (!\Zend_Validate::is(trim($post['fax']), 'NotEmpty')) {
                $error = true;
            }
             if (!\Zend_Validate::is(trim($post['concentration']), 'NotEmpty')) {
                $error = true;
            }
             if (!\Zend_Validate::is(trim($post['instructions']), 'NotEmpty')) {
                $error = true;
            }
            // if (\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
            //     $error = true;
            // }
            if ($error) {
                throw new \Exception();
            }
            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $transport = $this->_transportBuilder
                ->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope))
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    ]
                )
                ->setTemplateVars(['customer' => $postObject])
                ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
                ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
                ->setReplyTo($post['email'])
                ->getTransport();

            $transport->sendMessage();
            $this->inlineTranslation->resume();
            $this->messageManager->addSuccess(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->getDataPersistor()->clear('contact_us');
            $this->_redirect('thank-you-contact-us');
            return;
        } catch (\Exception $e) {
            $this->inlineTranslation->resume();
            $this->messageManager->addError(
                __('We can\'t process your request right now. Sorry, that\'s all we know.')
                // __($e->getMessage())
            );
            $this->getDataPersistor()->set('analytical-instrument-supplies-standards-custom-standards.html', $post);
            $this->_redirect('analytical-instrument-supplies-standards-custom-standards.html');
            return;
        }
    }

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

        return $this->dataPersistor;
    }
}
  • Please share your full code which you have tried yet. – Rakesh Jesadiya Jun 15 '17 at 4:59
  • Hi Rakesh, Ok I will post it in here – MazeStricks Jun 15 '17 at 5:02
3

app/code/Company/ModuleName/etc/adminhtml/system.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
        <system>
            <tab id="customformtab" translate="label" sortOrder="1">
                <label>Voucher</label>
            </tab>
            <section id="customform" showInDefault="1" showInStore="1" showInWebsite="1" translate="label" type="text">
                <label>Custom form</label>
                <tab>customformtab</tab>
                <resource>Company_ModuleName::company</resource>
                <group id="general" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="1" type="text">
                    <label>Contact form Settings</label>   
                   <field id="customer_email_sender" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="1" translate="label" type="select">
                        <label>Email Sender</label>
                        <source_model>Magento\Config\Model\Config\Source\Email\Identity</source_model>
                    </field>  
                </group>
            </section>
        </system>
</config>

app/code/Company/ModuleName/etc/email_templates.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
    <template area="frontend" file="customform.html" id="customform_general_customer_email_sender" label="Customform" module="Company_ModuleName" type="html"/>
</config>

app/code/Company/ModuleName/view/frontend/email/customform.html

<!--@subject Custom form {{var store.getFrontendName()}} @-->

{{template config_path="design/email/header_template"}}
Custom code of your template
{{template config_path="design/email/footer_template"}}

Change,

`const XML_PATH_EMAIL_TEMPLATE = 'customform/general/customer_email_sender';
| improve this answer | |
  • Hi Rakesh, Thanks man! I've been waiting for your answer! I will test this out also. I'll update you once this will work in my end. Thanks again – MazeStricks Jun 15 '17 at 5:39
  • Thanks! This worked in my end. but I added few modifications. Thanks again – MazeStricks Jun 15 '17 at 8:02
0

I don't think it is that difficult. If you have seperate form and works differently you don't need to extend the contact module controller.

There are few steps to follow:

  1. On your module you need to create "email_templates.xml" file.
  2. Create the template for the email
  3. And on your controller you need the instance of

Magento\Store\Model\StoreManagerInterface Magento\Framework\Mail\Template\TransportBuilder, Magento\Framework\Translate\Inline\StateInterface

Please follow https://webkul.com/blog/magento2-create-custom-email-templates/ this tutorial for detail codes and explanation.

I have created a simple working module following this.

Hope this is what you are looking for.

| improve this answer | |
  • Hi Anton, I have created an email template in the backend of the site in Marketing>Email Templates, I want to use that template if someone will fill out my custom form and submit it. – MazeStricks Jun 15 '17 at 5:21
  • You cannot create email template from admin, you can just extends existing email templates. If you have a requirement of managing separate type of email template you can just create new email template in module and it will be visible on admin on Marketing>Email Templates section too. Have you checked the link i have added on the answer? – aton1004 Jun 15 '17 at 5:24
  • Ok thank you for your answer aton. I will test this out. I'll update you once it will work in my end. Thanks – MazeStricks Jun 15 '17 at 5:27
  • sure if it helps, please don't forget to accept and vote the answer – aton1004 Jun 15 '17 at 5:29
  • Ok aton sure no problem. I may have some questions to you are you online all day? If you don't mind. Thanks – MazeStricks Jun 15 '17 at 5:31

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.