0

how I can create a secondary contact form with mangento2x, I want to customize a contact form for clients feedback, I saw a lot of extensions that do what I want but they are not free, is there an easy way to be able to do it?

0

Please follow below steps:

Step-1: go to "app" from root directory of Magento 2 and create new directory code. Then create two more directories in app/code, Namespace and Module Name. The final directory will look like this: app/code/Demo/Contact

Step-2: create registration.php file in app/code/Demo/Contact/ and paste below code into the file:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Demo_Contact',
    __DIR__
);

Step-3: create module.xml file in app/code/Demo/Contact/etc and paste below code into the file:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Demo_Contact" setup_version="0.0.1">
        <sequence>
            <module name="Magento_Contact"/>
        </sequence>
    </module>
</config>

Step-4: create di.xml file in app/code/Demo/Contact/etc and paste below code into the file:

<?xml version="1.0" encoding="UTF-8"?>
<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="Demo\Contact\Controller\Index\Post" />
</config>

Step-5: create email_templates.xml file in app/code/Demo/Contact/etc and paste below code into the file:

<?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 id="contact_email_email_template" label="Contact Form" file="submitted_form.html" type="html" module="Demo_Contact" area="adminhtml"/>
</config>

Step-6: create Post.php file in app/code/Demo/Contact/Controller/Index and paste below code into the file:

<?php
namespace Demo\Contact\Controller\Index;

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

class Post extends \Magento\Contact\Controller\Index\Post
{
    /**
     * @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['comment']), 'NotEmpty')) {
                $error = true;
            }

            if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                $error = true;
            }
            if (\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
                $error = true;
            }

            if (!\Zend_Validate::is(trim($post['custom_field_1']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['custom_field_2']), '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(['data' => $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('contact/index');
            return;
        } catch (\Exception $e) {
            $this->inlineTranslation->resume();
            $this->messageManager->addError(
                __('We can\'t process your request right now. Sorry, that\'s all we know.')
            );
            $this->getDataPersistor()->set('contact_us', $post);
            $this->_redirect('contact/index');
            return;
        }
    }

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

        return $this->dataPersistor;
    }
}

Step-7: create contact_index_index.xml file in app/code/Demo/Contact/view/frontend/layout and paste below code into the file:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="contactForm">
            <action method='setTemplate'>
                <argument name='template' xsi:type='string'>Demo_Contact::form.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Step-8: create form.phtml file in app/code/Demo/Contact/view/frontend/templates and paste below code into the file:

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<form class="form contact"
      action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
      id="contact-form"
      method="post"
      data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
      data-mage-init='{"validation":{}}'>
    <fieldset class="fieldset">
        <legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Write Us') ?></span></legend><br />
        <div class="field note no-label"><?php /* @escapeNotVerified */ echo __('Jot us a note and we’ll get back to you as quickly as possible.') ?></div>
        <div class="field name required">
            <label class="label" for="name"><span><?php /* @escapeNotVerified */ echo __('Name') ?></span></label>
            <div class="control">
                <input name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Name') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getPostValue('name') ?: $this->helper('Magento\Contact\Helper\Data')->getUserName()) ?>" class="input-text" type="text" data-validate="{required:true}"/>
            </div>
        </div>
        <div class="field email required">
            <label class="label" for="email"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
            <div class="control">
                <input name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getPostValue('email') ?: $this->helper('Magento\Contact\Helper\Data')->getUserEmail()) ?>" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}"/>
            </div>
        </div>
        <div class="field telephone">
            <label class="label" for="telephone"><span><?php /* @escapeNotVerified */ echo __('Phone Number') ?></span></label>
            <div class="control">
                <input name="telephone" id="telephone" title="<?php /* @escapeNotVerified */ echo __('Phone Number') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getPostValue('telephone')) ?>" class="input-text" type="text" />
            </div>
        </div>
        <div class="field comment required">
            <label class="label" for="comment"><span><?php /* @escapeNotVerified */ echo __('What’s on your mind?') ?></span></label>
            <div class="control">
                <textarea name="comment" id="comment" title="<?php /* @escapeNotVerified */ echo __('What’s on your mind?') ?>" class="input-text" cols="5" rows="3" data-validate="{required:true}"><?php echo $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getPostValue('comment')) ?></textarea>
            </div>
        </div>

        <div class="field custom_field_1 required">
            <label class="label" for="custom_field_1"><span><?php /* @escapeNotVerified */ echo __('Custom Field 1') ?></span></label>
            <div class="control">
                <input name="custom_field_1" id="custom_field_1" title="<?php /* @escapeNotVerified */ echo __('Custom Field 1') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getPostValue('custom_field_1') ?: "") ?>" class="input-text" type="text" data-validate="{required:true}"/>
            </div>
        </div>
        <div class="field custom_field_2 required">
            <label class="label" for="custom_field_2"><span><?php /* @escapeNotVerified */ echo __('Custom Field 2') ?></span></label>
            <div class="control">
                <input name="custom_field_2" id="custom_field_2" title="<?php /* @escapeNotVerified */ echo __('Custom Field 2') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getPostValue('custom_field_2') ?: "") ?>" class="input-text" type="text" data-validate="{required:true}"/>
            </div>
        </div>

        <?php echo $block->getChildHtml('form.additional.info'); ?>
    </fieldset>
    <div class="actions-toolbar">
        <div class="primary">
            <input type="hidden" name="hideit" id="hideit" value="" />
            <button type="submit" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>" class="action submit primary">
                <span><?php /* @escapeNotVerified */ echo __('Submit') ?></span>
            </button>
        </div>
    </div>
</form>

Step-9: create submitted_form.html file in app/code/Demo/Contact/view/adminhtml/email and paste below code into the file:

<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<!--@subject {{trans "Comment Form"}} @-->
<!--@vars {
"var data.comment":"Comment",
"var data.email":"Sender Email",
"var data.username":"Sender Name",
"var data.post_title":"Post Title"
"var data.custom_field_1":"Custom Field 1"
"var data.custom_field_2":"Custom Field 2"
} @-->

{{trans "Name: %name" name=$data.username}}
{{trans "Email: %email" email=$data.email}}
{{trans "Post Title: %post_title" post_title=$data.post_title}}
{{trans "Custom Field 1: %custom_field_1" custom_field_1=$data.custom_field_1}}
{{trans "Custom Field 2: %custom_field_2" custom_field_2=$data.custom_field_2}}

{{trans "Comment: %comment" comment=$data.comment}}
  • Hello Nilesh, i followed the instruction but i have a question for Step-8: create contact_index_index.xml is that right .xml or should be .php and when i'm done how i can introduce the contact form to CMS page – user3005390 Feb 1 '18 at 20:07
  • Kindly review, I have updated my answer – Nilesh Gosai Feb 2 '18 at 5:22

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.