How to create a custom form for sending email with file attachment in magento 2How to send mail programmaticlly in magento2?Pass Variable And Output In Custom Email TemplateMagento 2 Add review form on custom pageContact form does not send emailMagento2.2 Custom form not sending data via emailNot able to send email from custom moduleSecondary contact formContact Form in Magento 2 Custom Module is Not Sending EmailHow to add contact us form and functionality programmatically in frontend magento 2?How to save attachment in database using custom form in Magento 2?How to Create Custom Form in Magento2 Frontend?Magento 2 - Change the order of the Shipping fields on the Checkout pageHow to add a custom field to the frontend customer registration form in magento 2?change field labels in shipping address in order email in magento 1.9Magento 2 how to add extra validation to new Billing address form fields in checkout pageHow to override Customer registration fields to custom module in magento 2How to create custom form in Magento 2.2.3Magento 2.3 email attachment not working while sending custom emailplugin for custom field for contact form magento2
Why does my house heat up, even when it's cool outside?
Are required indicators necessary for radio buttons?
Don't these experiments suggest that locality has to be abandoned in the quantum realm?
Why can't an Airbus A330 dump fuel in an emergency?
How do I request a longer than normal leave of absense period for my wedding?
How much code would a codegolf golf if a codegolf could golf code?
Why we don't have vaccination against all diseases which are caused by microbes?
Were there 486SX revisions without an FPU on the die?
Solve a logarithmic equation by NSolve
Is “I am getting married with my sister” ambiguous?
Give function defaults arguments from a dictionary in Python
Why don't electrons take the shorter path in coils
map 5 unequal ranges to id
When translating the law, who ensures that the wording does not change the meaning of the law?
Why is 日本 read as "nihon" but not "nitsuhon"?
Exctract year, month, day from datetime2
Brexit and backstop: would changes require unanimous approval by all EU countries? Does Ireland hold a veto?
Justifying the use of directed energy weapons
How should I face my manager if I make a mistake because a senior coworker explained something incorrectly to me?
What is this symbol: semicircles facing eachother
How to analyze "dearly beloved"?
Why were movies shot on film shot at 24 frames per second?
How big would a Daddy Longlegs Spider need to be to kill an average Human?
What professions would a medieval village with a population of 100 need?
How to create a custom form for sending email with file attachment in magento 2
How to send mail programmaticlly in magento2?Pass Variable And Output In Custom Email TemplateMagento 2 Add review form on custom pageContact form does not send emailMagento2.2 Custom form not sending data via emailNot able to send email from custom moduleSecondary contact formContact Form in Magento 2 Custom Module is Not Sending EmailHow to add contact us form and functionality programmatically in frontend magento 2?How to save attachment in database using custom form in Magento 2?How to Create Custom Form in Magento2 Frontend?Magento 2 - Change the order of the Shipping fields on the Checkout pageHow to add a custom field to the frontend customer registration form in magento 2?change field labels in shipping address in order email in magento 1.9Magento 2 how to add extra validation to new Billing address form fields in checkout pageHow to override Customer registration fields to custom module in magento 2How to create custom form in Magento 2.2.3Magento 2.3 email attachment not working while sending custom emailplugin for custom field for contact form magento2
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
How to create a custom form for sending email in Magento 2
Fields are like
- First name
- Last name
- Address
- City
- State
- Zip code
- Phone
- Product type: checkbox Option like (1) One (2) Two
- File upload
- comment
magento2 email
add a comment |
How to create a custom form for sending email in Magento 2
Fields are like
- First name
- Last name
- Address
- City
- State
- Zip code
- Phone
- Product type: checkbox Option like (1) One (2) Two
- File upload
- comment
magento2 email
ashsmith.io/magento2/transactional-emails-in-magento-2
– Ravindrasinh Zala
Oct 26 '17 at 15:36
magento.stackexchange.com/questions/187855/…
– Ravindrasinh Zala
Oct 26 '17 at 15:38
magento.stackexchange.com/questions/132391/…
– Ravindrasinh Zala
Oct 26 '17 at 15:43
add a comment |
How to create a custom form for sending email in Magento 2
Fields are like
- First name
- Last name
- Address
- City
- State
- Zip code
- Phone
- Product type: checkbox Option like (1) One (2) Two
- File upload
- comment
magento2 email
How to create a custom form for sending email in Magento 2
Fields are like
- First name
- Last name
- Address
- City
- State
- Zip code
- Phone
- Product type: checkbox Option like (1) One (2) Two
- File upload
- comment
magento2 email
magento2 email
edited Aug 10 at 8:13
Ravindrasinh Zala
asked Oct 26 '17 at 15:19
Ravindrasinh ZalaRavindrasinh Zala
1,4195 silver badges24 bronze badges
1,4195 silver badges24 bronze badges
ashsmith.io/magento2/transactional-emails-in-magento-2
– Ravindrasinh Zala
Oct 26 '17 at 15:36
magento.stackexchange.com/questions/187855/…
– Ravindrasinh Zala
Oct 26 '17 at 15:38
magento.stackexchange.com/questions/132391/…
– Ravindrasinh Zala
Oct 26 '17 at 15:43
add a comment |
ashsmith.io/magento2/transactional-emails-in-magento-2
– Ravindrasinh Zala
Oct 26 '17 at 15:36
magento.stackexchange.com/questions/187855/…
– Ravindrasinh Zala
Oct 26 '17 at 15:38
magento.stackexchange.com/questions/132391/…
– Ravindrasinh Zala
Oct 26 '17 at 15:43
ashsmith.io/magento2/transactional-emails-in-magento-2
– Ravindrasinh Zala
Oct 26 '17 at 15:36
ashsmith.io/magento2/transactional-emails-in-magento-2
– Ravindrasinh Zala
Oct 26 '17 at 15:36
magento.stackexchange.com/questions/187855/…
– Ravindrasinh Zala
Oct 26 '17 at 15:38
magento.stackexchange.com/questions/187855/…
– Ravindrasinh Zala
Oct 26 '17 at 15:38
magento.stackexchange.com/questions/132391/…
– Ravindrasinh Zala
Oct 26 '17 at 15:43
magento.stackexchange.com/questions/132391/…
– Ravindrasinh Zala
Oct 26 '17 at 15:43
add a comment |
4 Answers
4
active
oldest
votes
Try below code in your controller
vendorname/modulename/controller/Index/index.php
<?php
/**
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleControllerIndex;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppRequestDataPersistorInterface;
class Index extends Action
MagentoFrameworkViewResultPage
*/
protected $context;
private $fileUploaderFactory;
private $fileSystem;
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
Filesystem $fileSystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
ModiaCformHelperData $helper,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
)
parent::__construct($context,$transportBuilder,$inlineTranslation, $scopeConfig );
$this->fileUploaderFactory = $fileUploaderFactory;
$this->fileSystem = $fileSystem;
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->helper = $helper;
$this->scopeConfig = $scopeConfig;
public function execute()
$post = $this->getRequest()->getPostValue();
$filesData = $this->getRequest()->getFiles('upload_document');
if ($filesData['name'])
$uploader = $this->fileUploaderFactory->create(['fileId' => 'upload_document']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$path = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('test-doc');
$result = $uploader->save($path);
$upload_document = 'test-doc'.$uploader->getUploadedFilename();
$filePath = $result['path'].$result['file'];
$fileName = $result['name'];
else
$upload_document = '';
$filePath = '';
$fileName = '';
$txt='<table>';
if($post['fname'])
$txt.='<tr><td><strong>Client Name</strong>:'.$post['fname'].'</td></tr>';
if($post['address'])
$txt.='<tr><td><strong>Address</strong>:'.$post['address'].'</td></tr>';
if($post['city'])
$txt.='<tr><td><strong>City</strong>:'.$post['city'].'</td></tr>';
if($post['state'])
$txt.='<tr><td><strong>State/Province</strong>:'.$post['state'].'</td></tr>';
if($post['zipcode'])
$txt.='<tr><td><strong>Zip Code</strong>:'.$post['zipcode'].'</td></tr>';
if($post['phone'])
$txt.='<tr><td><strong>Phone</strong>:'.$post['phone'].'</td></tr>';
if($post['email'])
$txt.='<tr><td><strong>Email</strong>:'.$post['email'].'</td></tr>';
if(!empty($post['project_type']))
$projecttypearray = implode(",",$post['project_type']);
$txt.='<tr><td><strong>Project Type</strong>:'.$projecttypearray.'</td></tr>';
if($post['comment'])
$txt.='<tr><td><strong>Comment</strong>:'.$post['comment'].'</td></tr>';
$txt.='</table>';
//echo $txt;
$customerName='Demo Form';
$message=$txt;
$userSubject= 'Demo From ';
$fromEmail= 'admin@gmail.com.com';
$fromName = 'Test Demo Form';
$templateVars = [
'store' => 1,
'customer_name' => $customerName,
'subject' => $userSubject,
'message' => $message
];
$from = ['email' => $fromEmail, 'name' => $fromName];
$this->inlineTranslation->suspend();
$to = 'test@gmail.com';
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$templateOptions = [
'area' => MagentoFrameworkAppArea::AREA_FRONTEND,
'store' => 1
];
$transport = $this->_transportBuilder->setTemplateIdentifier(5, $storeScope)
->setTemplateOptions($templateOptions)
->setTemplateVars($templateVars)
->setFrom($from)
->addTo($to)
->addAttachment($filePath, $fileName)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(__('Form successfully submitted'));
$this->_redirect('form');
vendorname/modulename/etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoFrameworkMailTemplateTransportBuilder" type="VendornameModulenameMagentoMailTemplateTransportBuilder" />
</config>
Vendorname/Modulename/Magento/Mail/Template/TransportBuilder.php
<?php
namespace VendornameModulenameMagentoMailTemplate;
class TransportBuilder extends MagentoFrameworkMailTemplateTransportBuilder
public function addAttachment($file, $name)
if (!empty($file) && file_exists($file))
$this->message
->createAttachment(
file_get_contents($file),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename($name)
);
return $this;
Vendorname/Modulename/view/frontend/templates/test.phtml
<div class="container">
<form class="form-horizontal" method="post" enctype="multipart/form-data" action="url/cform/index/index">
<div class="form-group">
<div class="row">
<div class="col-sm-12">
<label for="">Name</label>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="fname" placeholder="first name">
</div>
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="lname" placeholder="last name">
</div>
</div>
</div>
<div class="form-group">
<label for="">Address</label>
<textarea class="col-sm-12 form-control" rows="3" placeholder="" name="address"></textarea>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-5">
<label for="">City</label>
<input class="form-control" type="text" name="city" id="" placeholder="">
</div>
<div class="col-sm-4">
<label for="">State/Province</label>
<input class="form-control" type="text" name="state" id="" placeholder="">
</div>
<div class="col-sm-3">
<label for="">Zip Code</label>
<input class="form-control" type="text" name="zipcode" id="" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-8">
<label for="">Phone</label>
<div class="row">
<div class="col-sm-5">
<input class="form-control" type="text" id="" name="phone" placeholder="">
</div>
<div class="col-sm-2 phone-or">
<span>OR</span>
</div>
<div class="col-sm-5">
<input class="form-control" type="text" id="" placeholder="">
</div>
</div>
</div>
<div class="col-sm-4">
<label for="">Email</label>
<input class="form-control" type="email" id="email" name="email" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Project Type :</label>
</div>
<div class="col-sm-10">
<label class="checkbox-inline">
<input type="checkbox" id="" value="One1" name="project_type[]"> <span>Residential</span>
</label>
<label class="checkbox-inline">
<input type="checkbox" id="" value="One2" name="project_type[]"> <span>Commercial</span>
</label>
</div>
</div>
</div>
<div class="col-md-4 col-xs-12">
<input accept="image/*" name="upload_document" type="file" value="" />
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Comment :</label>
</div>
<div class="col-sm-10">
<textarea class="form-control comment" rows="3" name="comment" placeholder="additional information about your project"></textarea>
</div>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-primary">SUBMIT</button>
</div>
</form>
</div>
Now call in cms page
block class="MagentoFrameworkViewElementTemplate" template="Vendorname_Modulename::test.phtml"
I tried this code but it's not working
– kiran
Oct 4 '18 at 16:43
add a comment |
- Create a simple html form and submit data to your controller.
- Get all your post values in your controller and send mail using below function.
You can send mail using Zend_Mail() function.
// Get your post values
$firstname = "Dinesh";
$lastname = "Yadav";
// Send Mail functionality starts from here
$from = "from_email_address@example.com";
$nameFrom = "From Name";
$to = "to_email_address@example.com";
$nameTo = "To Name";
$body = "
<div>
<b>".$firstname."</b>
<i>".$lastname."</i>
</div>";
$email = new Zend_Mail();
$email->setSubject("Email Subject");
$email->setBodyHtml($body); // use it to send html data
//$email->setBodyText($body); // use it to send simple text data
$email->setFrom($from, $nameFrom);
$email->addTo($to, $nameTo);
$email->send();
add a comment |
app/code/Vendor/Cform/etc/module.xml
<?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="Vendor_Cform" setup_version="2.2.0">
</module>
</config>
app/code/Vendor/Cform/registration.php
MagentoFrameworkComponentComponentRegistrar::register(
MagentoFrameworkComponentComponentRegistrar::MODULE,
'Vendor_Cform',
__DIR__
);
app/code/Vendor/Cform/etc/frontend/routes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="cform" frontName="cform">
<module name="Vendor_Cform" />
</route>
</router>
</config>
app/code/Vendor/Cform/Setup/InstallSchema.php
<?php
namespace VendorCformSetup;
use MagentoFrameworkSetupInstallSchemaInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupSchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
$installer = $setup;
$installer->startSetup();
/**
* Create table 'vendor_contect'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('vendor_contect')
)->addColumn(
'contect_id',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Contect Id'
)->addColumn(
'name',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Name'
)->addColumn(
'email',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Email Id'
)->addColumn(
'telephone',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['nullable'=> false],
'Phone Number'
)->addColumn(
'comment',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'What’s on your mind?'
);
$installer->getConnection()->createTable($table);
app/code/Vendor/Cform/view/frontend/templates/form.phtml
<form id="contact-form" class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo $this->getUrl("cform/index/index")?>">
<h1><?= $block->escapeHtml(__('Contact Form')) ?></h1>
<fieldset class="fieldset">
<div class="field name">
<label class="label" for="name"><span><?= $block->escapeHtml(__('Name')) ?></span></label>
<div class="control">
<input name="name" id="name" class="input-text" type="text" />
</div>
</div>
<div class="field email">
<label class="label" for="email"><span><?= $block->escapeHtml(__('Email')) ?></span></label>
<div class="control">
<input name="email" id="email" class="input-text" type="email" />
</div>
</div>
<div class="field telephone">
<label class="label" for="telephone"><span><?= $block->escapeHtml(__('Phone Number')) ?></span></label>
<div class="control">
<input name="telephone" id="telephone" class="input-text" type="text" />
</div>
</div>
<div class="field comment">
<label class="label" for="comment"><span><?= $block->escapeHtml(__('What’s on your mind?')) ?></span></label>
<div class="control">
<textarea name="comment" id="comment" class="input-text" cols="5" rows="3" ></textarea>
</div>
</div>
<?= $block->getChildHtml('form.additional.info') ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" id="add" title="" class="action submit primary">
<span><?= $block->escapeHtml(__('Submit')) ?></span>
</button>
</div>
</div>
</form>
<script>
require(['jquery'],function($)
$(document).ready(function()
$("#add").click(function()
var customurl = "<?php echo $this->getUrl("cform/index/index") ?>";
$.ajax(
url: customurl,
type: "POST",
data: $(this).closest('form').serialize(),
dataType: "json",
success: function(result)
console.log(result);
);
$('#contact-form')[0].reset();
return false;
);
);
);
</script>
app/code/Vendor/Cform/Controller/Index/index.php
<?php
namespace VendorCformControllerIndex;
use MagentoFrameworkAppActionAction;
class Index extends Action
public function __construct(
MagentoFrameworkAppActionContext $context
)
parent::__construct($context);
public function execute()
$post = $this->getRequest()->getPostValue();
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$data = $objectManager->create('MconnectCformModelCform');
$data->setData($post);
$data->save();
/* echo "hello";
exit; */
$this->messageManager->addSuccess(__('Form successfully submitted'));
app/code/Vendor/Cform/Model/Cform.php
<?php
namespace VendorCformModel;
class Cform extends MagentoFrameworkModelAbstractModel
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelResourceModelCform');
app/code/Vendor/Cform/Model/ResourceModel/Cform.php
<?php
namespace VendorCformModelResourceModel;
class Cform extends MagentoFrameworkModelResourceModelDbAbstractDb
protected $storeManager;
public function __construct(
MagentoFrameworkModelResourceModelDbContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
$connectionName = null
)
parent::__construct($context, $connectionName);
$this->storeManager = $storeManager;
protected function _construct()
$this->_init('vendor_contect', 'contect_id');
app/code/Vendor/Cform/Model/ResourceModel/Cform/Collection.php
<?php
namespace VendorCformModelResourceModelCform;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
class Collection extends AbstractCollection
protected $_idFieldName = VendorCformModelCform::CONTECT_ID;
/**
* Define resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelCform', 'VendorCformModelResourceModelCform');
CMS page Call
block class="MagentoFrameworkViewElementTemplate" template="Vendor_Cform::form.phtml"
app/code/Vendor/Cform/view/frontend/layout/contactform_index_index.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="VendorContactFormBlockForm" name="contactForm" template="Vendor_ContactForm::form.phtml">
<container name="form.additional.info" label="Form Additional Info"/>
</block>
</referenceContainer>
</body>
</page>
Is this linked to your other answer? I know in test.phtml, it refers to "cform" in the form action - I assume it's this?
– Thomas Harding
Jan 14 at 15:48
add a comment |
Note: Contact is vendor and Us is module.Here i am posting my form data to my frontend controller Post.php
step 1: Create email_templates.xml in app/code/Contact/Us/etc
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
<template id="send_email_email_template" label="Email Form" file="email_template.html" type="text" module="Contact_Us" area="frontend"/>
step 2: Create email_template.html in app/code/Contact/Us/view/frontend/email
<!--@subject xMage-support@-->
<!--@vars
"var data.comment":"xMage-support",
"var data.email":"support@xmagestore.com",
"var data.name":"XMageStore"
@-->
template config_path="design/email/header_template"
trans "Dear %name" name=$data.name
trans "we received your request regarding %queryregarding"
queryregarding=$data.requestType
template config_path="design/email/footer_template"
Step 3: Create Post.php controller in app/code/Contact/Us/Controller/Post
<?php
namespace ContactUsControllerIndex;
class Post extends MagentoFrameworkAppActionAction
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkEscaper
*/
protected $_escaper;
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
* @param MagentoStoreModelStoreManagerInterface $storeManager
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkEscaper $escaper
)
parent::__construct($context);
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
$this->_escaper = $escaper;
/**
* Post user question
*
* @return void
* @throws Exception
*/
public function execute()
$post = $this->getRequest()->getPostValue();
if (!$post)
$this->_redirect('/');
return;
$this->inlineTranslation->suspend();
try
$recipientMail = $this->getRequest()->getPostValue('email');
$postObject = new MagentoFrameworkDataObject();
$postObject->setData($post);
$error = false;
$sender = [
'name' => 'xMageStore',
'email' => 'support@xmagestore.com',
];
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$transport = $this->_transportBuilder
->setTemplateIdentifier('send_email_email_template') // this code we have mentioned in the email_templates.xml
->setTemplateOptions(
[
'area' => MagentoFrameworkAppArea::AREA_FRONTEND, // this is using frontend area to get the template file
'store' => MagentoStoreModelStore::DEFAULT_STORE_ID,
]
)
->setTemplateVars(['data' => $postObject])
->setFrom($sender)
->addTo($recipientMail)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(
__('Thanks for contacting us. We'll respond to you very soon.')
);
$this->_redirect('/');
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->_redirect('/');
return;
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f198838%2fhow-to-create-a-custom-form-for-sending-email-with-file-attachment-in-magento-2%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Try below code in your controller
vendorname/modulename/controller/Index/index.php
<?php
/**
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleControllerIndex;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppRequestDataPersistorInterface;
class Index extends Action
MagentoFrameworkViewResultPage
*/
protected $context;
private $fileUploaderFactory;
private $fileSystem;
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
Filesystem $fileSystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
ModiaCformHelperData $helper,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
)
parent::__construct($context,$transportBuilder,$inlineTranslation, $scopeConfig );
$this->fileUploaderFactory = $fileUploaderFactory;
$this->fileSystem = $fileSystem;
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->helper = $helper;
$this->scopeConfig = $scopeConfig;
public function execute()
$post = $this->getRequest()->getPostValue();
$filesData = $this->getRequest()->getFiles('upload_document');
if ($filesData['name'])
$uploader = $this->fileUploaderFactory->create(['fileId' => 'upload_document']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$path = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('test-doc');
$result = $uploader->save($path);
$upload_document = 'test-doc'.$uploader->getUploadedFilename();
$filePath = $result['path'].$result['file'];
$fileName = $result['name'];
else
$upload_document = '';
$filePath = '';
$fileName = '';
$txt='<table>';
if($post['fname'])
$txt.='<tr><td><strong>Client Name</strong>:'.$post['fname'].'</td></tr>';
if($post['address'])
$txt.='<tr><td><strong>Address</strong>:'.$post['address'].'</td></tr>';
if($post['city'])
$txt.='<tr><td><strong>City</strong>:'.$post['city'].'</td></tr>';
if($post['state'])
$txt.='<tr><td><strong>State/Province</strong>:'.$post['state'].'</td></tr>';
if($post['zipcode'])
$txt.='<tr><td><strong>Zip Code</strong>:'.$post['zipcode'].'</td></tr>';
if($post['phone'])
$txt.='<tr><td><strong>Phone</strong>:'.$post['phone'].'</td></tr>';
if($post['email'])
$txt.='<tr><td><strong>Email</strong>:'.$post['email'].'</td></tr>';
if(!empty($post['project_type']))
$projecttypearray = implode(",",$post['project_type']);
$txt.='<tr><td><strong>Project Type</strong>:'.$projecttypearray.'</td></tr>';
if($post['comment'])
$txt.='<tr><td><strong>Comment</strong>:'.$post['comment'].'</td></tr>';
$txt.='</table>';
//echo $txt;
$customerName='Demo Form';
$message=$txt;
$userSubject= 'Demo From ';
$fromEmail= 'admin@gmail.com.com';
$fromName = 'Test Demo Form';
$templateVars = [
'store' => 1,
'customer_name' => $customerName,
'subject' => $userSubject,
'message' => $message
];
$from = ['email' => $fromEmail, 'name' => $fromName];
$this->inlineTranslation->suspend();
$to = 'test@gmail.com';
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$templateOptions = [
'area' => MagentoFrameworkAppArea::AREA_FRONTEND,
'store' => 1
];
$transport = $this->_transportBuilder->setTemplateIdentifier(5, $storeScope)
->setTemplateOptions($templateOptions)
->setTemplateVars($templateVars)
->setFrom($from)
->addTo($to)
->addAttachment($filePath, $fileName)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(__('Form successfully submitted'));
$this->_redirect('form');
vendorname/modulename/etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoFrameworkMailTemplateTransportBuilder" type="VendornameModulenameMagentoMailTemplateTransportBuilder" />
</config>
Vendorname/Modulename/Magento/Mail/Template/TransportBuilder.php
<?php
namespace VendornameModulenameMagentoMailTemplate;
class TransportBuilder extends MagentoFrameworkMailTemplateTransportBuilder
public function addAttachment($file, $name)
if (!empty($file) && file_exists($file))
$this->message
->createAttachment(
file_get_contents($file),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename($name)
);
return $this;
Vendorname/Modulename/view/frontend/templates/test.phtml
<div class="container">
<form class="form-horizontal" method="post" enctype="multipart/form-data" action="url/cform/index/index">
<div class="form-group">
<div class="row">
<div class="col-sm-12">
<label for="">Name</label>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="fname" placeholder="first name">
</div>
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="lname" placeholder="last name">
</div>
</div>
</div>
<div class="form-group">
<label for="">Address</label>
<textarea class="col-sm-12 form-control" rows="3" placeholder="" name="address"></textarea>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-5">
<label for="">City</label>
<input class="form-control" type="text" name="city" id="" placeholder="">
</div>
<div class="col-sm-4">
<label for="">State/Province</label>
<input class="form-control" type="text" name="state" id="" placeholder="">
</div>
<div class="col-sm-3">
<label for="">Zip Code</label>
<input class="form-control" type="text" name="zipcode" id="" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-8">
<label for="">Phone</label>
<div class="row">
<div class="col-sm-5">
<input class="form-control" type="text" id="" name="phone" placeholder="">
</div>
<div class="col-sm-2 phone-or">
<span>OR</span>
</div>
<div class="col-sm-5">
<input class="form-control" type="text" id="" placeholder="">
</div>
</div>
</div>
<div class="col-sm-4">
<label for="">Email</label>
<input class="form-control" type="email" id="email" name="email" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Project Type :</label>
</div>
<div class="col-sm-10">
<label class="checkbox-inline">
<input type="checkbox" id="" value="One1" name="project_type[]"> <span>Residential</span>
</label>
<label class="checkbox-inline">
<input type="checkbox" id="" value="One2" name="project_type[]"> <span>Commercial</span>
</label>
</div>
</div>
</div>
<div class="col-md-4 col-xs-12">
<input accept="image/*" name="upload_document" type="file" value="" />
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Comment :</label>
</div>
<div class="col-sm-10">
<textarea class="form-control comment" rows="3" name="comment" placeholder="additional information about your project"></textarea>
</div>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-primary">SUBMIT</button>
</div>
</form>
</div>
Now call in cms page
block class="MagentoFrameworkViewElementTemplate" template="Vendorname_Modulename::test.phtml"
I tried this code but it's not working
– kiran
Oct 4 '18 at 16:43
add a comment |
Try below code in your controller
vendorname/modulename/controller/Index/index.php
<?php
/**
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleControllerIndex;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppRequestDataPersistorInterface;
class Index extends Action
MagentoFrameworkViewResultPage
*/
protected $context;
private $fileUploaderFactory;
private $fileSystem;
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
Filesystem $fileSystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
ModiaCformHelperData $helper,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
)
parent::__construct($context,$transportBuilder,$inlineTranslation, $scopeConfig );
$this->fileUploaderFactory = $fileUploaderFactory;
$this->fileSystem = $fileSystem;
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->helper = $helper;
$this->scopeConfig = $scopeConfig;
public function execute()
$post = $this->getRequest()->getPostValue();
$filesData = $this->getRequest()->getFiles('upload_document');
if ($filesData['name'])
$uploader = $this->fileUploaderFactory->create(['fileId' => 'upload_document']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$path = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('test-doc');
$result = $uploader->save($path);
$upload_document = 'test-doc'.$uploader->getUploadedFilename();
$filePath = $result['path'].$result['file'];
$fileName = $result['name'];
else
$upload_document = '';
$filePath = '';
$fileName = '';
$txt='<table>';
if($post['fname'])
$txt.='<tr><td><strong>Client Name</strong>:'.$post['fname'].'</td></tr>';
if($post['address'])
$txt.='<tr><td><strong>Address</strong>:'.$post['address'].'</td></tr>';
if($post['city'])
$txt.='<tr><td><strong>City</strong>:'.$post['city'].'</td></tr>';
if($post['state'])
$txt.='<tr><td><strong>State/Province</strong>:'.$post['state'].'</td></tr>';
if($post['zipcode'])
$txt.='<tr><td><strong>Zip Code</strong>:'.$post['zipcode'].'</td></tr>';
if($post['phone'])
$txt.='<tr><td><strong>Phone</strong>:'.$post['phone'].'</td></tr>';
if($post['email'])
$txt.='<tr><td><strong>Email</strong>:'.$post['email'].'</td></tr>';
if(!empty($post['project_type']))
$projecttypearray = implode(",",$post['project_type']);
$txt.='<tr><td><strong>Project Type</strong>:'.$projecttypearray.'</td></tr>';
if($post['comment'])
$txt.='<tr><td><strong>Comment</strong>:'.$post['comment'].'</td></tr>';
$txt.='</table>';
//echo $txt;
$customerName='Demo Form';
$message=$txt;
$userSubject= 'Demo From ';
$fromEmail= 'admin@gmail.com.com';
$fromName = 'Test Demo Form';
$templateVars = [
'store' => 1,
'customer_name' => $customerName,
'subject' => $userSubject,
'message' => $message
];
$from = ['email' => $fromEmail, 'name' => $fromName];
$this->inlineTranslation->suspend();
$to = 'test@gmail.com';
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$templateOptions = [
'area' => MagentoFrameworkAppArea::AREA_FRONTEND,
'store' => 1
];
$transport = $this->_transportBuilder->setTemplateIdentifier(5, $storeScope)
->setTemplateOptions($templateOptions)
->setTemplateVars($templateVars)
->setFrom($from)
->addTo($to)
->addAttachment($filePath, $fileName)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(__('Form successfully submitted'));
$this->_redirect('form');
vendorname/modulename/etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoFrameworkMailTemplateTransportBuilder" type="VendornameModulenameMagentoMailTemplateTransportBuilder" />
</config>
Vendorname/Modulename/Magento/Mail/Template/TransportBuilder.php
<?php
namespace VendornameModulenameMagentoMailTemplate;
class TransportBuilder extends MagentoFrameworkMailTemplateTransportBuilder
public function addAttachment($file, $name)
if (!empty($file) && file_exists($file))
$this->message
->createAttachment(
file_get_contents($file),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename($name)
);
return $this;
Vendorname/Modulename/view/frontend/templates/test.phtml
<div class="container">
<form class="form-horizontal" method="post" enctype="multipart/form-data" action="url/cform/index/index">
<div class="form-group">
<div class="row">
<div class="col-sm-12">
<label for="">Name</label>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="fname" placeholder="first name">
</div>
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="lname" placeholder="last name">
</div>
</div>
</div>
<div class="form-group">
<label for="">Address</label>
<textarea class="col-sm-12 form-control" rows="3" placeholder="" name="address"></textarea>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-5">
<label for="">City</label>
<input class="form-control" type="text" name="city" id="" placeholder="">
</div>
<div class="col-sm-4">
<label for="">State/Province</label>
<input class="form-control" type="text" name="state" id="" placeholder="">
</div>
<div class="col-sm-3">
<label for="">Zip Code</label>
<input class="form-control" type="text" name="zipcode" id="" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-8">
<label for="">Phone</label>
<div class="row">
<div class="col-sm-5">
<input class="form-control" type="text" id="" name="phone" placeholder="">
</div>
<div class="col-sm-2 phone-or">
<span>OR</span>
</div>
<div class="col-sm-5">
<input class="form-control" type="text" id="" placeholder="">
</div>
</div>
</div>
<div class="col-sm-4">
<label for="">Email</label>
<input class="form-control" type="email" id="email" name="email" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Project Type :</label>
</div>
<div class="col-sm-10">
<label class="checkbox-inline">
<input type="checkbox" id="" value="One1" name="project_type[]"> <span>Residential</span>
</label>
<label class="checkbox-inline">
<input type="checkbox" id="" value="One2" name="project_type[]"> <span>Commercial</span>
</label>
</div>
</div>
</div>
<div class="col-md-4 col-xs-12">
<input accept="image/*" name="upload_document" type="file" value="" />
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Comment :</label>
</div>
<div class="col-sm-10">
<textarea class="form-control comment" rows="3" name="comment" placeholder="additional information about your project"></textarea>
</div>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-primary">SUBMIT</button>
</div>
</form>
</div>
Now call in cms page
block class="MagentoFrameworkViewElementTemplate" template="Vendorname_Modulename::test.phtml"
I tried this code but it's not working
– kiran
Oct 4 '18 at 16:43
add a comment |
Try below code in your controller
vendorname/modulename/controller/Index/index.php
<?php
/**
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleControllerIndex;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppRequestDataPersistorInterface;
class Index extends Action
MagentoFrameworkViewResultPage
*/
protected $context;
private $fileUploaderFactory;
private $fileSystem;
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
Filesystem $fileSystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
ModiaCformHelperData $helper,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
)
parent::__construct($context,$transportBuilder,$inlineTranslation, $scopeConfig );
$this->fileUploaderFactory = $fileUploaderFactory;
$this->fileSystem = $fileSystem;
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->helper = $helper;
$this->scopeConfig = $scopeConfig;
public function execute()
$post = $this->getRequest()->getPostValue();
$filesData = $this->getRequest()->getFiles('upload_document');
if ($filesData['name'])
$uploader = $this->fileUploaderFactory->create(['fileId' => 'upload_document']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$path = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('test-doc');
$result = $uploader->save($path);
$upload_document = 'test-doc'.$uploader->getUploadedFilename();
$filePath = $result['path'].$result['file'];
$fileName = $result['name'];
else
$upload_document = '';
$filePath = '';
$fileName = '';
$txt='<table>';
if($post['fname'])
$txt.='<tr><td><strong>Client Name</strong>:'.$post['fname'].'</td></tr>';
if($post['address'])
$txt.='<tr><td><strong>Address</strong>:'.$post['address'].'</td></tr>';
if($post['city'])
$txt.='<tr><td><strong>City</strong>:'.$post['city'].'</td></tr>';
if($post['state'])
$txt.='<tr><td><strong>State/Province</strong>:'.$post['state'].'</td></tr>';
if($post['zipcode'])
$txt.='<tr><td><strong>Zip Code</strong>:'.$post['zipcode'].'</td></tr>';
if($post['phone'])
$txt.='<tr><td><strong>Phone</strong>:'.$post['phone'].'</td></tr>';
if($post['email'])
$txt.='<tr><td><strong>Email</strong>:'.$post['email'].'</td></tr>';
if(!empty($post['project_type']))
$projecttypearray = implode(",",$post['project_type']);
$txt.='<tr><td><strong>Project Type</strong>:'.$projecttypearray.'</td></tr>';
if($post['comment'])
$txt.='<tr><td><strong>Comment</strong>:'.$post['comment'].'</td></tr>';
$txt.='</table>';
//echo $txt;
$customerName='Demo Form';
$message=$txt;
$userSubject= 'Demo From ';
$fromEmail= 'admin@gmail.com.com';
$fromName = 'Test Demo Form';
$templateVars = [
'store' => 1,
'customer_name' => $customerName,
'subject' => $userSubject,
'message' => $message
];
$from = ['email' => $fromEmail, 'name' => $fromName];
$this->inlineTranslation->suspend();
$to = 'test@gmail.com';
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$templateOptions = [
'area' => MagentoFrameworkAppArea::AREA_FRONTEND,
'store' => 1
];
$transport = $this->_transportBuilder->setTemplateIdentifier(5, $storeScope)
->setTemplateOptions($templateOptions)
->setTemplateVars($templateVars)
->setFrom($from)
->addTo($to)
->addAttachment($filePath, $fileName)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(__('Form successfully submitted'));
$this->_redirect('form');
vendorname/modulename/etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoFrameworkMailTemplateTransportBuilder" type="VendornameModulenameMagentoMailTemplateTransportBuilder" />
</config>
Vendorname/Modulename/Magento/Mail/Template/TransportBuilder.php
<?php
namespace VendornameModulenameMagentoMailTemplate;
class TransportBuilder extends MagentoFrameworkMailTemplateTransportBuilder
public function addAttachment($file, $name)
if (!empty($file) && file_exists($file))
$this->message
->createAttachment(
file_get_contents($file),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename($name)
);
return $this;
Vendorname/Modulename/view/frontend/templates/test.phtml
<div class="container">
<form class="form-horizontal" method="post" enctype="multipart/form-data" action="url/cform/index/index">
<div class="form-group">
<div class="row">
<div class="col-sm-12">
<label for="">Name</label>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="fname" placeholder="first name">
</div>
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="lname" placeholder="last name">
</div>
</div>
</div>
<div class="form-group">
<label for="">Address</label>
<textarea class="col-sm-12 form-control" rows="3" placeholder="" name="address"></textarea>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-5">
<label for="">City</label>
<input class="form-control" type="text" name="city" id="" placeholder="">
</div>
<div class="col-sm-4">
<label for="">State/Province</label>
<input class="form-control" type="text" name="state" id="" placeholder="">
</div>
<div class="col-sm-3">
<label for="">Zip Code</label>
<input class="form-control" type="text" name="zipcode" id="" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-8">
<label for="">Phone</label>
<div class="row">
<div class="col-sm-5">
<input class="form-control" type="text" id="" name="phone" placeholder="">
</div>
<div class="col-sm-2 phone-or">
<span>OR</span>
</div>
<div class="col-sm-5">
<input class="form-control" type="text" id="" placeholder="">
</div>
</div>
</div>
<div class="col-sm-4">
<label for="">Email</label>
<input class="form-control" type="email" id="email" name="email" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Project Type :</label>
</div>
<div class="col-sm-10">
<label class="checkbox-inline">
<input type="checkbox" id="" value="One1" name="project_type[]"> <span>Residential</span>
</label>
<label class="checkbox-inline">
<input type="checkbox" id="" value="One2" name="project_type[]"> <span>Commercial</span>
</label>
</div>
</div>
</div>
<div class="col-md-4 col-xs-12">
<input accept="image/*" name="upload_document" type="file" value="" />
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Comment :</label>
</div>
<div class="col-sm-10">
<textarea class="form-control comment" rows="3" name="comment" placeholder="additional information about your project"></textarea>
</div>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-primary">SUBMIT</button>
</div>
</form>
</div>
Now call in cms page
block class="MagentoFrameworkViewElementTemplate" template="Vendorname_Modulename::test.phtml"
Try below code in your controller
vendorname/modulename/controller/Index/index.php
<?php
/**
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleControllerIndex;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppRequestDataPersistorInterface;
class Index extends Action
MagentoFrameworkViewResultPage
*/
protected $context;
private $fileUploaderFactory;
private $fileSystem;
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
Filesystem $fileSystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
ModiaCformHelperData $helper,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
)
parent::__construct($context,$transportBuilder,$inlineTranslation, $scopeConfig );
$this->fileUploaderFactory = $fileUploaderFactory;
$this->fileSystem = $fileSystem;
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->helper = $helper;
$this->scopeConfig = $scopeConfig;
public function execute()
$post = $this->getRequest()->getPostValue();
$filesData = $this->getRequest()->getFiles('upload_document');
if ($filesData['name'])
$uploader = $this->fileUploaderFactory->create(['fileId' => 'upload_document']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$path = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('test-doc');
$result = $uploader->save($path);
$upload_document = 'test-doc'.$uploader->getUploadedFilename();
$filePath = $result['path'].$result['file'];
$fileName = $result['name'];
else
$upload_document = '';
$filePath = '';
$fileName = '';
$txt='<table>';
if($post['fname'])
$txt.='<tr><td><strong>Client Name</strong>:'.$post['fname'].'</td></tr>';
if($post['address'])
$txt.='<tr><td><strong>Address</strong>:'.$post['address'].'</td></tr>';
if($post['city'])
$txt.='<tr><td><strong>City</strong>:'.$post['city'].'</td></tr>';
if($post['state'])
$txt.='<tr><td><strong>State/Province</strong>:'.$post['state'].'</td></tr>';
if($post['zipcode'])
$txt.='<tr><td><strong>Zip Code</strong>:'.$post['zipcode'].'</td></tr>';
if($post['phone'])
$txt.='<tr><td><strong>Phone</strong>:'.$post['phone'].'</td></tr>';
if($post['email'])
$txt.='<tr><td><strong>Email</strong>:'.$post['email'].'</td></tr>';
if(!empty($post['project_type']))
$projecttypearray = implode(",",$post['project_type']);
$txt.='<tr><td><strong>Project Type</strong>:'.$projecttypearray.'</td></tr>';
if($post['comment'])
$txt.='<tr><td><strong>Comment</strong>:'.$post['comment'].'</td></tr>';
$txt.='</table>';
//echo $txt;
$customerName='Demo Form';
$message=$txt;
$userSubject= 'Demo From ';
$fromEmail= 'admin@gmail.com.com';
$fromName = 'Test Demo Form';
$templateVars = [
'store' => 1,
'customer_name' => $customerName,
'subject' => $userSubject,
'message' => $message
];
$from = ['email' => $fromEmail, 'name' => $fromName];
$this->inlineTranslation->suspend();
$to = 'test@gmail.com';
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$templateOptions = [
'area' => MagentoFrameworkAppArea::AREA_FRONTEND,
'store' => 1
];
$transport = $this->_transportBuilder->setTemplateIdentifier(5, $storeScope)
->setTemplateOptions($templateOptions)
->setTemplateVars($templateVars)
->setFrom($from)
->addTo($to)
->addAttachment($filePath, $fileName)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(__('Form successfully submitted'));
$this->_redirect('form');
vendorname/modulename/etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoFrameworkMailTemplateTransportBuilder" type="VendornameModulenameMagentoMailTemplateTransportBuilder" />
</config>
Vendorname/Modulename/Magento/Mail/Template/TransportBuilder.php
<?php
namespace VendornameModulenameMagentoMailTemplate;
class TransportBuilder extends MagentoFrameworkMailTemplateTransportBuilder
public function addAttachment($file, $name)
if (!empty($file) && file_exists($file))
$this->message
->createAttachment(
file_get_contents($file),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename($name)
);
return $this;
Vendorname/Modulename/view/frontend/templates/test.phtml
<div class="container">
<form class="form-horizontal" method="post" enctype="multipart/form-data" action="url/cform/index/index">
<div class="form-group">
<div class="row">
<div class="col-sm-12">
<label for="">Name</label>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="fname" placeholder="first name">
</div>
<div class="col-sm-6">
<input class="form-control" type="text" id="" name="lname" placeholder="last name">
</div>
</div>
</div>
<div class="form-group">
<label for="">Address</label>
<textarea class="col-sm-12 form-control" rows="3" placeholder="" name="address"></textarea>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-5">
<label for="">City</label>
<input class="form-control" type="text" name="city" id="" placeholder="">
</div>
<div class="col-sm-4">
<label for="">State/Province</label>
<input class="form-control" type="text" name="state" id="" placeholder="">
</div>
<div class="col-sm-3">
<label for="">Zip Code</label>
<input class="form-control" type="text" name="zipcode" id="" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-8">
<label for="">Phone</label>
<div class="row">
<div class="col-sm-5">
<input class="form-control" type="text" id="" name="phone" placeholder="">
</div>
<div class="col-sm-2 phone-or">
<span>OR</span>
</div>
<div class="col-sm-5">
<input class="form-control" type="text" id="" placeholder="">
</div>
</div>
</div>
<div class="col-sm-4">
<label for="">Email</label>
<input class="form-control" type="email" id="email" name="email" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Project Type :</label>
</div>
<div class="col-sm-10">
<label class="checkbox-inline">
<input type="checkbox" id="" value="One1" name="project_type[]"> <span>Residential</span>
</label>
<label class="checkbox-inline">
<input type="checkbox" id="" value="One2" name="project_type[]"> <span>Commercial</span>
</label>
</div>
</div>
</div>
<div class="col-md-4 col-xs-12">
<input accept="image/*" name="upload_document" type="file" value="" />
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<label for="">Comment :</label>
</div>
<div class="col-sm-10">
<textarea class="form-control comment" rows="3" name="comment" placeholder="additional information about your project"></textarea>
</div>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-primary">SUBMIT</button>
</div>
</form>
</div>
Now call in cms page
block class="MagentoFrameworkViewElementTemplate" template="Vendorname_Modulename::test.phtml"
edited Apr 23 '18 at 17:50
answered Nov 16 '17 at 10:35
Ravindrasinh ZalaRavindrasinh Zala
1,4195 silver badges24 bronze badges
1,4195 silver badges24 bronze badges
I tried this code but it's not working
– kiran
Oct 4 '18 at 16:43
add a comment |
I tried this code but it's not working
– kiran
Oct 4 '18 at 16:43
I tried this code but it's not working
– kiran
Oct 4 '18 at 16:43
I tried this code but it's not working
– kiran
Oct 4 '18 at 16:43
add a comment |
- Create a simple html form and submit data to your controller.
- Get all your post values in your controller and send mail using below function.
You can send mail using Zend_Mail() function.
// Get your post values
$firstname = "Dinesh";
$lastname = "Yadav";
// Send Mail functionality starts from here
$from = "from_email_address@example.com";
$nameFrom = "From Name";
$to = "to_email_address@example.com";
$nameTo = "To Name";
$body = "
<div>
<b>".$firstname."</b>
<i>".$lastname."</i>
</div>";
$email = new Zend_Mail();
$email->setSubject("Email Subject");
$email->setBodyHtml($body); // use it to send html data
//$email->setBodyText($body); // use it to send simple text data
$email->setFrom($from, $nameFrom);
$email->addTo($to, $nameTo);
$email->send();
add a comment |
- Create a simple html form and submit data to your controller.
- Get all your post values in your controller and send mail using below function.
You can send mail using Zend_Mail() function.
// Get your post values
$firstname = "Dinesh";
$lastname = "Yadav";
// Send Mail functionality starts from here
$from = "from_email_address@example.com";
$nameFrom = "From Name";
$to = "to_email_address@example.com";
$nameTo = "To Name";
$body = "
<div>
<b>".$firstname."</b>
<i>".$lastname."</i>
</div>";
$email = new Zend_Mail();
$email->setSubject("Email Subject");
$email->setBodyHtml($body); // use it to send html data
//$email->setBodyText($body); // use it to send simple text data
$email->setFrom($from, $nameFrom);
$email->addTo($to, $nameTo);
$email->send();
add a comment |
- Create a simple html form and submit data to your controller.
- Get all your post values in your controller and send mail using below function.
You can send mail using Zend_Mail() function.
// Get your post values
$firstname = "Dinesh";
$lastname = "Yadav";
// Send Mail functionality starts from here
$from = "from_email_address@example.com";
$nameFrom = "From Name";
$to = "to_email_address@example.com";
$nameTo = "To Name";
$body = "
<div>
<b>".$firstname."</b>
<i>".$lastname."</i>
</div>";
$email = new Zend_Mail();
$email->setSubject("Email Subject");
$email->setBodyHtml($body); // use it to send html data
//$email->setBodyText($body); // use it to send simple text data
$email->setFrom($from, $nameFrom);
$email->addTo($to, $nameTo);
$email->send();
- Create a simple html form and submit data to your controller.
- Get all your post values in your controller and send mail using below function.
You can send mail using Zend_Mail() function.
// Get your post values
$firstname = "Dinesh";
$lastname = "Yadav";
// Send Mail functionality starts from here
$from = "from_email_address@example.com";
$nameFrom = "From Name";
$to = "to_email_address@example.com";
$nameTo = "To Name";
$body = "
<div>
<b>".$firstname."</b>
<i>".$lastname."</i>
</div>";
$email = new Zend_Mail();
$email->setSubject("Email Subject");
$email->setBodyHtml($body); // use it to send html data
//$email->setBodyText($body); // use it to send simple text data
$email->setFrom($from, $nameFrom);
$email->addTo($to, $nameTo);
$email->send();
answered Oct 27 '17 at 7:35
Dinesh YadavDinesh Yadav
4,4041 gold badge9 silver badges38 bronze badges
4,4041 gold badge9 silver badges38 bronze badges
add a comment |
add a comment |
app/code/Vendor/Cform/etc/module.xml
<?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="Vendor_Cform" setup_version="2.2.0">
</module>
</config>
app/code/Vendor/Cform/registration.php
MagentoFrameworkComponentComponentRegistrar::register(
MagentoFrameworkComponentComponentRegistrar::MODULE,
'Vendor_Cform',
__DIR__
);
app/code/Vendor/Cform/etc/frontend/routes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="cform" frontName="cform">
<module name="Vendor_Cform" />
</route>
</router>
</config>
app/code/Vendor/Cform/Setup/InstallSchema.php
<?php
namespace VendorCformSetup;
use MagentoFrameworkSetupInstallSchemaInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupSchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
$installer = $setup;
$installer->startSetup();
/**
* Create table 'vendor_contect'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('vendor_contect')
)->addColumn(
'contect_id',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Contect Id'
)->addColumn(
'name',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Name'
)->addColumn(
'email',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Email Id'
)->addColumn(
'telephone',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['nullable'=> false],
'Phone Number'
)->addColumn(
'comment',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'What’s on your mind?'
);
$installer->getConnection()->createTable($table);
app/code/Vendor/Cform/view/frontend/templates/form.phtml
<form id="contact-form" class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo $this->getUrl("cform/index/index")?>">
<h1><?= $block->escapeHtml(__('Contact Form')) ?></h1>
<fieldset class="fieldset">
<div class="field name">
<label class="label" for="name"><span><?= $block->escapeHtml(__('Name')) ?></span></label>
<div class="control">
<input name="name" id="name" class="input-text" type="text" />
</div>
</div>
<div class="field email">
<label class="label" for="email"><span><?= $block->escapeHtml(__('Email')) ?></span></label>
<div class="control">
<input name="email" id="email" class="input-text" type="email" />
</div>
</div>
<div class="field telephone">
<label class="label" for="telephone"><span><?= $block->escapeHtml(__('Phone Number')) ?></span></label>
<div class="control">
<input name="telephone" id="telephone" class="input-text" type="text" />
</div>
</div>
<div class="field comment">
<label class="label" for="comment"><span><?= $block->escapeHtml(__('What’s on your mind?')) ?></span></label>
<div class="control">
<textarea name="comment" id="comment" class="input-text" cols="5" rows="3" ></textarea>
</div>
</div>
<?= $block->getChildHtml('form.additional.info') ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" id="add" title="" class="action submit primary">
<span><?= $block->escapeHtml(__('Submit')) ?></span>
</button>
</div>
</div>
</form>
<script>
require(['jquery'],function($)
$(document).ready(function()
$("#add").click(function()
var customurl = "<?php echo $this->getUrl("cform/index/index") ?>";
$.ajax(
url: customurl,
type: "POST",
data: $(this).closest('form').serialize(),
dataType: "json",
success: function(result)
console.log(result);
);
$('#contact-form')[0].reset();
return false;
);
);
);
</script>
app/code/Vendor/Cform/Controller/Index/index.php
<?php
namespace VendorCformControllerIndex;
use MagentoFrameworkAppActionAction;
class Index extends Action
public function __construct(
MagentoFrameworkAppActionContext $context
)
parent::__construct($context);
public function execute()
$post = $this->getRequest()->getPostValue();
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$data = $objectManager->create('MconnectCformModelCform');
$data->setData($post);
$data->save();
/* echo "hello";
exit; */
$this->messageManager->addSuccess(__('Form successfully submitted'));
app/code/Vendor/Cform/Model/Cform.php
<?php
namespace VendorCformModel;
class Cform extends MagentoFrameworkModelAbstractModel
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelResourceModelCform');
app/code/Vendor/Cform/Model/ResourceModel/Cform.php
<?php
namespace VendorCformModelResourceModel;
class Cform extends MagentoFrameworkModelResourceModelDbAbstractDb
protected $storeManager;
public function __construct(
MagentoFrameworkModelResourceModelDbContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
$connectionName = null
)
parent::__construct($context, $connectionName);
$this->storeManager = $storeManager;
protected function _construct()
$this->_init('vendor_contect', 'contect_id');
app/code/Vendor/Cform/Model/ResourceModel/Cform/Collection.php
<?php
namespace VendorCformModelResourceModelCform;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
class Collection extends AbstractCollection
protected $_idFieldName = VendorCformModelCform::CONTECT_ID;
/**
* Define resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelCform', 'VendorCformModelResourceModelCform');
CMS page Call
block class="MagentoFrameworkViewElementTemplate" template="Vendor_Cform::form.phtml"
app/code/Vendor/Cform/view/frontend/layout/contactform_index_index.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="VendorContactFormBlockForm" name="contactForm" template="Vendor_ContactForm::form.phtml">
<container name="form.additional.info" label="Form Additional Info"/>
</block>
</referenceContainer>
</body>
</page>
Is this linked to your other answer? I know in test.phtml, it refers to "cform" in the form action - I assume it's this?
– Thomas Harding
Jan 14 at 15:48
add a comment |
app/code/Vendor/Cform/etc/module.xml
<?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="Vendor_Cform" setup_version="2.2.0">
</module>
</config>
app/code/Vendor/Cform/registration.php
MagentoFrameworkComponentComponentRegistrar::register(
MagentoFrameworkComponentComponentRegistrar::MODULE,
'Vendor_Cform',
__DIR__
);
app/code/Vendor/Cform/etc/frontend/routes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="cform" frontName="cform">
<module name="Vendor_Cform" />
</route>
</router>
</config>
app/code/Vendor/Cform/Setup/InstallSchema.php
<?php
namespace VendorCformSetup;
use MagentoFrameworkSetupInstallSchemaInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupSchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
$installer = $setup;
$installer->startSetup();
/**
* Create table 'vendor_contect'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('vendor_contect')
)->addColumn(
'contect_id',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Contect Id'
)->addColumn(
'name',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Name'
)->addColumn(
'email',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Email Id'
)->addColumn(
'telephone',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['nullable'=> false],
'Phone Number'
)->addColumn(
'comment',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'What’s on your mind?'
);
$installer->getConnection()->createTable($table);
app/code/Vendor/Cform/view/frontend/templates/form.phtml
<form id="contact-form" class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo $this->getUrl("cform/index/index")?>">
<h1><?= $block->escapeHtml(__('Contact Form')) ?></h1>
<fieldset class="fieldset">
<div class="field name">
<label class="label" for="name"><span><?= $block->escapeHtml(__('Name')) ?></span></label>
<div class="control">
<input name="name" id="name" class="input-text" type="text" />
</div>
</div>
<div class="field email">
<label class="label" for="email"><span><?= $block->escapeHtml(__('Email')) ?></span></label>
<div class="control">
<input name="email" id="email" class="input-text" type="email" />
</div>
</div>
<div class="field telephone">
<label class="label" for="telephone"><span><?= $block->escapeHtml(__('Phone Number')) ?></span></label>
<div class="control">
<input name="telephone" id="telephone" class="input-text" type="text" />
</div>
</div>
<div class="field comment">
<label class="label" for="comment"><span><?= $block->escapeHtml(__('What’s on your mind?')) ?></span></label>
<div class="control">
<textarea name="comment" id="comment" class="input-text" cols="5" rows="3" ></textarea>
</div>
</div>
<?= $block->getChildHtml('form.additional.info') ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" id="add" title="" class="action submit primary">
<span><?= $block->escapeHtml(__('Submit')) ?></span>
</button>
</div>
</div>
</form>
<script>
require(['jquery'],function($)
$(document).ready(function()
$("#add").click(function()
var customurl = "<?php echo $this->getUrl("cform/index/index") ?>";
$.ajax(
url: customurl,
type: "POST",
data: $(this).closest('form').serialize(),
dataType: "json",
success: function(result)
console.log(result);
);
$('#contact-form')[0].reset();
return false;
);
);
);
</script>
app/code/Vendor/Cform/Controller/Index/index.php
<?php
namespace VendorCformControllerIndex;
use MagentoFrameworkAppActionAction;
class Index extends Action
public function __construct(
MagentoFrameworkAppActionContext $context
)
parent::__construct($context);
public function execute()
$post = $this->getRequest()->getPostValue();
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$data = $objectManager->create('MconnectCformModelCform');
$data->setData($post);
$data->save();
/* echo "hello";
exit; */
$this->messageManager->addSuccess(__('Form successfully submitted'));
app/code/Vendor/Cform/Model/Cform.php
<?php
namespace VendorCformModel;
class Cform extends MagentoFrameworkModelAbstractModel
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelResourceModelCform');
app/code/Vendor/Cform/Model/ResourceModel/Cform.php
<?php
namespace VendorCformModelResourceModel;
class Cform extends MagentoFrameworkModelResourceModelDbAbstractDb
protected $storeManager;
public function __construct(
MagentoFrameworkModelResourceModelDbContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
$connectionName = null
)
parent::__construct($context, $connectionName);
$this->storeManager = $storeManager;
protected function _construct()
$this->_init('vendor_contect', 'contect_id');
app/code/Vendor/Cform/Model/ResourceModel/Cform/Collection.php
<?php
namespace VendorCformModelResourceModelCform;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
class Collection extends AbstractCollection
protected $_idFieldName = VendorCformModelCform::CONTECT_ID;
/**
* Define resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelCform', 'VendorCformModelResourceModelCform');
CMS page Call
block class="MagentoFrameworkViewElementTemplate" template="Vendor_Cform::form.phtml"
app/code/Vendor/Cform/view/frontend/layout/contactform_index_index.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="VendorContactFormBlockForm" name="contactForm" template="Vendor_ContactForm::form.phtml">
<container name="form.additional.info" label="Form Additional Info"/>
</block>
</referenceContainer>
</body>
</page>
Is this linked to your other answer? I know in test.phtml, it refers to "cform" in the form action - I assume it's this?
– Thomas Harding
Jan 14 at 15:48
add a comment |
app/code/Vendor/Cform/etc/module.xml
<?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="Vendor_Cform" setup_version="2.2.0">
</module>
</config>
app/code/Vendor/Cform/registration.php
MagentoFrameworkComponentComponentRegistrar::register(
MagentoFrameworkComponentComponentRegistrar::MODULE,
'Vendor_Cform',
__DIR__
);
app/code/Vendor/Cform/etc/frontend/routes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="cform" frontName="cform">
<module name="Vendor_Cform" />
</route>
</router>
</config>
app/code/Vendor/Cform/Setup/InstallSchema.php
<?php
namespace VendorCformSetup;
use MagentoFrameworkSetupInstallSchemaInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupSchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
$installer = $setup;
$installer->startSetup();
/**
* Create table 'vendor_contect'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('vendor_contect')
)->addColumn(
'contect_id',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Contect Id'
)->addColumn(
'name',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Name'
)->addColumn(
'email',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Email Id'
)->addColumn(
'telephone',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['nullable'=> false],
'Phone Number'
)->addColumn(
'comment',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'What’s on your mind?'
);
$installer->getConnection()->createTable($table);
app/code/Vendor/Cform/view/frontend/templates/form.phtml
<form id="contact-form" class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo $this->getUrl("cform/index/index")?>">
<h1><?= $block->escapeHtml(__('Contact Form')) ?></h1>
<fieldset class="fieldset">
<div class="field name">
<label class="label" for="name"><span><?= $block->escapeHtml(__('Name')) ?></span></label>
<div class="control">
<input name="name" id="name" class="input-text" type="text" />
</div>
</div>
<div class="field email">
<label class="label" for="email"><span><?= $block->escapeHtml(__('Email')) ?></span></label>
<div class="control">
<input name="email" id="email" class="input-text" type="email" />
</div>
</div>
<div class="field telephone">
<label class="label" for="telephone"><span><?= $block->escapeHtml(__('Phone Number')) ?></span></label>
<div class="control">
<input name="telephone" id="telephone" class="input-text" type="text" />
</div>
</div>
<div class="field comment">
<label class="label" for="comment"><span><?= $block->escapeHtml(__('What’s on your mind?')) ?></span></label>
<div class="control">
<textarea name="comment" id="comment" class="input-text" cols="5" rows="3" ></textarea>
</div>
</div>
<?= $block->getChildHtml('form.additional.info') ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" id="add" title="" class="action submit primary">
<span><?= $block->escapeHtml(__('Submit')) ?></span>
</button>
</div>
</div>
</form>
<script>
require(['jquery'],function($)
$(document).ready(function()
$("#add").click(function()
var customurl = "<?php echo $this->getUrl("cform/index/index") ?>";
$.ajax(
url: customurl,
type: "POST",
data: $(this).closest('form').serialize(),
dataType: "json",
success: function(result)
console.log(result);
);
$('#contact-form')[0].reset();
return false;
);
);
);
</script>
app/code/Vendor/Cform/Controller/Index/index.php
<?php
namespace VendorCformControllerIndex;
use MagentoFrameworkAppActionAction;
class Index extends Action
public function __construct(
MagentoFrameworkAppActionContext $context
)
parent::__construct($context);
public function execute()
$post = $this->getRequest()->getPostValue();
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$data = $objectManager->create('MconnectCformModelCform');
$data->setData($post);
$data->save();
/* echo "hello";
exit; */
$this->messageManager->addSuccess(__('Form successfully submitted'));
app/code/Vendor/Cform/Model/Cform.php
<?php
namespace VendorCformModel;
class Cform extends MagentoFrameworkModelAbstractModel
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelResourceModelCform');
app/code/Vendor/Cform/Model/ResourceModel/Cform.php
<?php
namespace VendorCformModelResourceModel;
class Cform extends MagentoFrameworkModelResourceModelDbAbstractDb
protected $storeManager;
public function __construct(
MagentoFrameworkModelResourceModelDbContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
$connectionName = null
)
parent::__construct($context, $connectionName);
$this->storeManager = $storeManager;
protected function _construct()
$this->_init('vendor_contect', 'contect_id');
app/code/Vendor/Cform/Model/ResourceModel/Cform/Collection.php
<?php
namespace VendorCformModelResourceModelCform;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
class Collection extends AbstractCollection
protected $_idFieldName = VendorCformModelCform::CONTECT_ID;
/**
* Define resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelCform', 'VendorCformModelResourceModelCform');
CMS page Call
block class="MagentoFrameworkViewElementTemplate" template="Vendor_Cform::form.phtml"
app/code/Vendor/Cform/view/frontend/layout/contactform_index_index.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="VendorContactFormBlockForm" name="contactForm" template="Vendor_ContactForm::form.phtml">
<container name="form.additional.info" label="Form Additional Info"/>
</block>
</referenceContainer>
</body>
</page>
app/code/Vendor/Cform/etc/module.xml
<?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="Vendor_Cform" setup_version="2.2.0">
</module>
</config>
app/code/Vendor/Cform/registration.php
MagentoFrameworkComponentComponentRegistrar::register(
MagentoFrameworkComponentComponentRegistrar::MODULE,
'Vendor_Cform',
__DIR__
);
app/code/Vendor/Cform/etc/frontend/routes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="cform" frontName="cform">
<module name="Vendor_Cform" />
</route>
</router>
</config>
app/code/Vendor/Cform/Setup/InstallSchema.php
<?php
namespace VendorCformSetup;
use MagentoFrameworkSetupInstallSchemaInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupSchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
$installer = $setup;
$installer->startSetup();
/**
* Create table 'vendor_contect'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('vendor_contect')
)->addColumn(
'contect_id',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Contect Id'
)->addColumn(
'name',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Name'
)->addColumn(
'email',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'Email Id'
)->addColumn(
'telephone',
MagentoFrameworkDBDdlTable::TYPE_INTEGER,
null,
['nullable'=> false],
'Phone Number'
)->addColumn(
'comment',
MagentoFrameworkDBDdlTable::TYPE_TEXT,
255,
['nullable' => false],
'What’s on your mind?'
);
$installer->getConnection()->createTable($table);
app/code/Vendor/Cform/view/frontend/templates/form.phtml
<form id="contact-form" class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo $this->getUrl("cform/index/index")?>">
<h1><?= $block->escapeHtml(__('Contact Form')) ?></h1>
<fieldset class="fieldset">
<div class="field name">
<label class="label" for="name"><span><?= $block->escapeHtml(__('Name')) ?></span></label>
<div class="control">
<input name="name" id="name" class="input-text" type="text" />
</div>
</div>
<div class="field email">
<label class="label" for="email"><span><?= $block->escapeHtml(__('Email')) ?></span></label>
<div class="control">
<input name="email" id="email" class="input-text" type="email" />
</div>
</div>
<div class="field telephone">
<label class="label" for="telephone"><span><?= $block->escapeHtml(__('Phone Number')) ?></span></label>
<div class="control">
<input name="telephone" id="telephone" class="input-text" type="text" />
</div>
</div>
<div class="field comment">
<label class="label" for="comment"><span><?= $block->escapeHtml(__('What’s on your mind?')) ?></span></label>
<div class="control">
<textarea name="comment" id="comment" class="input-text" cols="5" rows="3" ></textarea>
</div>
</div>
<?= $block->getChildHtml('form.additional.info') ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<input type="hidden" name="hideit" id="hideit" value="" />
<button type="submit" id="add" title="" class="action submit primary">
<span><?= $block->escapeHtml(__('Submit')) ?></span>
</button>
</div>
</div>
</form>
<script>
require(['jquery'],function($)
$(document).ready(function()
$("#add").click(function()
var customurl = "<?php echo $this->getUrl("cform/index/index") ?>";
$.ajax(
url: customurl,
type: "POST",
data: $(this).closest('form').serialize(),
dataType: "json",
success: function(result)
console.log(result);
);
$('#contact-form')[0].reset();
return false;
);
);
);
</script>
app/code/Vendor/Cform/Controller/Index/index.php
<?php
namespace VendorCformControllerIndex;
use MagentoFrameworkAppActionAction;
class Index extends Action
public function __construct(
MagentoFrameworkAppActionContext $context
)
parent::__construct($context);
public function execute()
$post = $this->getRequest()->getPostValue();
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$data = $objectManager->create('MconnectCformModelCform');
$data->setData($post);
$data->save();
/* echo "hello";
exit; */
$this->messageManager->addSuccess(__('Form successfully submitted'));
app/code/Vendor/Cform/Model/Cform.php
<?php
namespace VendorCformModel;
class Cform extends MagentoFrameworkModelAbstractModel
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelResourceModelCform');
app/code/Vendor/Cform/Model/ResourceModel/Cform.php
<?php
namespace VendorCformModelResourceModel;
class Cform extends MagentoFrameworkModelResourceModelDbAbstractDb
protected $storeManager;
public function __construct(
MagentoFrameworkModelResourceModelDbContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
$connectionName = null
)
parent::__construct($context, $connectionName);
$this->storeManager = $storeManager;
protected function _construct()
$this->_init('vendor_contect', 'contect_id');
app/code/Vendor/Cform/Model/ResourceModel/Cform/Collection.php
<?php
namespace VendorCformModelResourceModelCform;
use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
class Collection extends AbstractCollection
protected $_idFieldName = VendorCformModelCform::CONTECT_ID;
/**
* Define resource model
*
* @return void
*/
protected function _construct()
$this->_init('VendorCformModelCform', 'VendorCformModelResourceModelCform');
CMS page Call
block class="MagentoFrameworkViewElementTemplate" template="Vendor_Cform::form.phtml"
app/code/Vendor/Cform/view/frontend/layout/contactform_index_index.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="VendorContactFormBlockForm" name="contactForm" template="Vendor_ContactForm::form.phtml">
<container name="form.additional.info" label="Form Additional Info"/>
</block>
</referenceContainer>
</body>
</page>
answered Apr 11 '18 at 12:32
Ravindrasinh ZalaRavindrasinh Zala
1,4195 silver badges24 bronze badges
1,4195 silver badges24 bronze badges
Is this linked to your other answer? I know in test.phtml, it refers to "cform" in the form action - I assume it's this?
– Thomas Harding
Jan 14 at 15:48
add a comment |
Is this linked to your other answer? I know in test.phtml, it refers to "cform" in the form action - I assume it's this?
– Thomas Harding
Jan 14 at 15:48
Is this linked to your other answer? I know in test.phtml, it refers to "cform" in the form action - I assume it's this?
– Thomas Harding
Jan 14 at 15:48
Is this linked to your other answer? I know in test.phtml, it refers to "cform" in the form action - I assume it's this?
– Thomas Harding
Jan 14 at 15:48
add a comment |
Note: Contact is vendor and Us is module.Here i am posting my form data to my frontend controller Post.php
step 1: Create email_templates.xml in app/code/Contact/Us/etc
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
<template id="send_email_email_template" label="Email Form" file="email_template.html" type="text" module="Contact_Us" area="frontend"/>
step 2: Create email_template.html in app/code/Contact/Us/view/frontend/email
<!--@subject xMage-support@-->
<!--@vars
"var data.comment":"xMage-support",
"var data.email":"support@xmagestore.com",
"var data.name":"XMageStore"
@-->
template config_path="design/email/header_template"
trans "Dear %name" name=$data.name
trans "we received your request regarding %queryregarding"
queryregarding=$data.requestType
template config_path="design/email/footer_template"
Step 3: Create Post.php controller in app/code/Contact/Us/Controller/Post
<?php
namespace ContactUsControllerIndex;
class Post extends MagentoFrameworkAppActionAction
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkEscaper
*/
protected $_escaper;
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
* @param MagentoStoreModelStoreManagerInterface $storeManager
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkEscaper $escaper
)
parent::__construct($context);
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
$this->_escaper = $escaper;
/**
* Post user question
*
* @return void
* @throws Exception
*/
public function execute()
$post = $this->getRequest()->getPostValue();
if (!$post)
$this->_redirect('/');
return;
$this->inlineTranslation->suspend();
try
$recipientMail = $this->getRequest()->getPostValue('email');
$postObject = new MagentoFrameworkDataObject();
$postObject->setData($post);
$error = false;
$sender = [
'name' => 'xMageStore',
'email' => 'support@xmagestore.com',
];
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$transport = $this->_transportBuilder
->setTemplateIdentifier('send_email_email_template') // this code we have mentioned in the email_templates.xml
->setTemplateOptions(
[
'area' => MagentoFrameworkAppArea::AREA_FRONTEND, // this is using frontend area to get the template file
'store' => MagentoStoreModelStore::DEFAULT_STORE_ID,
]
)
->setTemplateVars(['data' => $postObject])
->setFrom($sender)
->addTo($recipientMail)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(
__('Thanks for contacting us. We'll respond to you very soon.')
);
$this->_redirect('/');
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->_redirect('/');
return;
add a comment |
Note: Contact is vendor and Us is module.Here i am posting my form data to my frontend controller Post.php
step 1: Create email_templates.xml in app/code/Contact/Us/etc
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
<template id="send_email_email_template" label="Email Form" file="email_template.html" type="text" module="Contact_Us" area="frontend"/>
step 2: Create email_template.html in app/code/Contact/Us/view/frontend/email
<!--@subject xMage-support@-->
<!--@vars
"var data.comment":"xMage-support",
"var data.email":"support@xmagestore.com",
"var data.name":"XMageStore"
@-->
template config_path="design/email/header_template"
trans "Dear %name" name=$data.name
trans "we received your request regarding %queryregarding"
queryregarding=$data.requestType
template config_path="design/email/footer_template"
Step 3: Create Post.php controller in app/code/Contact/Us/Controller/Post
<?php
namespace ContactUsControllerIndex;
class Post extends MagentoFrameworkAppActionAction
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkEscaper
*/
protected $_escaper;
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
* @param MagentoStoreModelStoreManagerInterface $storeManager
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkEscaper $escaper
)
parent::__construct($context);
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
$this->_escaper = $escaper;
/**
* Post user question
*
* @return void
* @throws Exception
*/
public function execute()
$post = $this->getRequest()->getPostValue();
if (!$post)
$this->_redirect('/');
return;
$this->inlineTranslation->suspend();
try
$recipientMail = $this->getRequest()->getPostValue('email');
$postObject = new MagentoFrameworkDataObject();
$postObject->setData($post);
$error = false;
$sender = [
'name' => 'xMageStore',
'email' => 'support@xmagestore.com',
];
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$transport = $this->_transportBuilder
->setTemplateIdentifier('send_email_email_template') // this code we have mentioned in the email_templates.xml
->setTemplateOptions(
[
'area' => MagentoFrameworkAppArea::AREA_FRONTEND, // this is using frontend area to get the template file
'store' => MagentoStoreModelStore::DEFAULT_STORE_ID,
]
)
->setTemplateVars(['data' => $postObject])
->setFrom($sender)
->addTo($recipientMail)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(
__('Thanks for contacting us. We'll respond to you very soon.')
);
$this->_redirect('/');
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->_redirect('/');
return;
add a comment |
Note: Contact is vendor and Us is module.Here i am posting my form data to my frontend controller Post.php
step 1: Create email_templates.xml in app/code/Contact/Us/etc
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
<template id="send_email_email_template" label="Email Form" file="email_template.html" type="text" module="Contact_Us" area="frontend"/>
step 2: Create email_template.html in app/code/Contact/Us/view/frontend/email
<!--@subject xMage-support@-->
<!--@vars
"var data.comment":"xMage-support",
"var data.email":"support@xmagestore.com",
"var data.name":"XMageStore"
@-->
template config_path="design/email/header_template"
trans "Dear %name" name=$data.name
trans "we received your request regarding %queryregarding"
queryregarding=$data.requestType
template config_path="design/email/footer_template"
Step 3: Create Post.php controller in app/code/Contact/Us/Controller/Post
<?php
namespace ContactUsControllerIndex;
class Post extends MagentoFrameworkAppActionAction
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkEscaper
*/
protected $_escaper;
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
* @param MagentoStoreModelStoreManagerInterface $storeManager
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkEscaper $escaper
)
parent::__construct($context);
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
$this->_escaper = $escaper;
/**
* Post user question
*
* @return void
* @throws Exception
*/
public function execute()
$post = $this->getRequest()->getPostValue();
if (!$post)
$this->_redirect('/');
return;
$this->inlineTranslation->suspend();
try
$recipientMail = $this->getRequest()->getPostValue('email');
$postObject = new MagentoFrameworkDataObject();
$postObject->setData($post);
$error = false;
$sender = [
'name' => 'xMageStore',
'email' => 'support@xmagestore.com',
];
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$transport = $this->_transportBuilder
->setTemplateIdentifier('send_email_email_template') // this code we have mentioned in the email_templates.xml
->setTemplateOptions(
[
'area' => MagentoFrameworkAppArea::AREA_FRONTEND, // this is using frontend area to get the template file
'store' => MagentoStoreModelStore::DEFAULT_STORE_ID,
]
)
->setTemplateVars(['data' => $postObject])
->setFrom($sender)
->addTo($recipientMail)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(
__('Thanks for contacting us. We'll respond to you very soon.')
);
$this->_redirect('/');
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->_redirect('/');
return;
Note: Contact is vendor and Us is module.Here i am posting my form data to my frontend controller Post.php
step 1: Create email_templates.xml in app/code/Contact/Us/etc
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
<template id="send_email_email_template" label="Email Form" file="email_template.html" type="text" module="Contact_Us" area="frontend"/>
step 2: Create email_template.html in app/code/Contact/Us/view/frontend/email
<!--@subject xMage-support@-->
<!--@vars
"var data.comment":"xMage-support",
"var data.email":"support@xmagestore.com",
"var data.name":"XMageStore"
@-->
template config_path="design/email/header_template"
trans "Dear %name" name=$data.name
trans "we received your request regarding %queryregarding"
queryregarding=$data.requestType
template config_path="design/email/footer_template"
Step 3: Create Post.php controller in app/code/Contact/Us/Controller/Post
<?php
namespace ContactUsControllerIndex;
class Post extends MagentoFrameworkAppActionAction
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;
/**
* @var MagentoFrameworkTranslateInlineStateInterface
*/
protected $inlineTranslation;
/**
* @var MagentoFrameworkAppConfigScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var MagentoFrameworkEscaper
*/
protected $_escaper;
/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
* @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
* @param MagentoStoreModelStoreManagerInterface $storeManager
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkEscaper $escaper
)
parent::__construct($context);
$this->_transportBuilder = $transportBuilder;
$this->inlineTranslation = $inlineTranslation;
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
$this->_escaper = $escaper;
/**
* Post user question
*
* @return void
* @throws Exception
*/
public function execute()
$post = $this->getRequest()->getPostValue();
if (!$post)
$this->_redirect('/');
return;
$this->inlineTranslation->suspend();
try
$recipientMail = $this->getRequest()->getPostValue('email');
$postObject = new MagentoFrameworkDataObject();
$postObject->setData($post);
$error = false;
$sender = [
'name' => 'xMageStore',
'email' => 'support@xmagestore.com',
];
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$transport = $this->_transportBuilder
->setTemplateIdentifier('send_email_email_template') // this code we have mentioned in the email_templates.xml
->setTemplateOptions(
[
'area' => MagentoFrameworkAppArea::AREA_FRONTEND, // this is using frontend area to get the template file
'store' => MagentoStoreModelStore::DEFAULT_STORE_ID,
]
)
->setTemplateVars(['data' => $postObject])
->setFrom($sender)
->addTo($recipientMail)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
$this->messageManager->addSuccess(
__('Thanks for contacting us. We'll respond to you very soon.')
);
$this->_redirect('/');
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->_redirect('/');
return;
answered Aug 9 at 11:59
Gaurav KumarGaurav Kumar
163 bronze badges
163 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f198838%2fhow-to-create-a-custom-form-for-sending-email-with-file-attachment-in-magento-2%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
ashsmith.io/magento2/transactional-emails-in-magento-2
– Ravindrasinh Zala
Oct 26 '17 at 15:36
magento.stackexchange.com/questions/187855/…
– Ravindrasinh Zala
Oct 26 '17 at 15:38
magento.stackexchange.com/questions/132391/…
– Ravindrasinh Zala
Oct 26 '17 at 15:43