当前位置: 技术文章>> Magento 2:在电子邮件模板中添加条件语句

文章标题:Magento 2:在电子邮件模板中添加条件语句
  • 文章分类: Magento
  • 12638 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


步骤1:在以下路径创建博客文件“索引.php”

app/code/Vendor/Extension/Block/Index

然后添加代码,如下所示

<?php
 
namespace Vendor\Extension\Block\Index;
 
class Index extends \Magento\Framework\View\Element\Template
{
    public function __construct(\Magento\Catalog\Block\Product\Context $context, array $data = [])
    {
        parent::__construct($context, $data);
    }
 
    protected function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
}

步骤 2:在以下路径创建控制器文件“索引.php”

app/code/Vendor/Extension/Controller/Index

然后添加以下代码片段

<?php
 
namespace Vendor\Extension\Controller\Index;
 
class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
}

第 3 步:在以下路径创建控制器文件.php

app/code/Vendor/Extension/Controller/Index/Post.php

然后添加以下代码片段

<?php
namespace Vendor\Extension\Controller\Index;   
use Magento\Store\Model\StoreManagerInterface;
 
class Post extends \Magento\Framework\App\Action\Action
{    
    protected $_inlineTranslation;
    protected $_transportBuilder;
    protected $_scopeConfig;
    protected $_logLoggerInterface;
    protected $storeManager;
     
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Psr\Log\LoggerInterface $loggerInterface,
        StoreManagerInterface $storeManager,
        array $data = []
        )
    {
        $this->_inlineTranslation = $inlineTranslation;
        $this->_transportBuilder = $transportBuilder;
        $this->_scopeConfig = $scopeConfig;
        $this->_logLoggerInterface = $loggerInterface;
        $this->messageManager = $context->getMessageManager();
        $this->storeManager = $storeManager;
         
        parent::__construct($context);         
    }
     
    public function execute()
    {        
        try
        {
            $post = $this->getRequest()->getPost();
          // Send Mail
            $this->_inlineTranslation->suspend();
            $sender = [
                'name' => $post['name'],
                'email' => $post['email']
            ];
             
            $transport = $this->_transportBuilder
            ->setTemplateIdentifier('customemail_email_template')
            ->setTemplateOptions(
                [
                    'area' => 'frontend',
                    'store' => $this->storeManager->getStore()->getId()
                ]
                )
               
                ->setTemplateVars([
                    'name2'  => $post['name'],
                    'email2'  => $post['email']
                ])
                ->setFromByScope($sender)
                ->addTo($post['email'],$post['name'])
                ->getTransport();
         
                $transport->sendMessage();  
                $this->_inlineTranslation->resume();
                $this->messageManager->addSuccess('Email sent successfully');
               
                $this->_redirect('email/index/index');
               
        } catch(\Exception $e){
            $this->messageManager->addErrorMessage("Something Went Wrong");
        }          
         
    }
}

步骤 4:为以下路径的正面表单显示创建一个“email_index_index.xml”文件

app/code/Vendor/Extension/view/frontend/layout

然后添加以下代码段

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
 
    <head>
        <title>Inquiery Form</title>
    </head>
 
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Extension\Block\Index\Index" name="customermail_index_index" template="Vendor_Extension::form.phtml"/>
        </referenceContainer>
    </body>
</page>

步骤 5:在以下路径创建表单模板“form.phtml”

app/code/Vendor/Extension/view/frontend/templates

现在添加以下代码片段

<form  enctype="multipart/form-data" action="<?php echo $block->getBaseUrl().'email/index/post/';?>" name="customemaildata" method="post" id="contactForm-1" data-hasrequired="<?php echo __('* Required Fields') ?>" data-mage-init='{"validation":{}}'>
    <fieldset class="fieldset">
            <div class="field email required">
                <label class="label" for="email"> Product Name :-</label>
                <div class="control">
                   <select name="name" id="name">
                    <option value="0">Please Select</option>
                    <option value="1">Product - 1</option>
                    <option value="2">Product - 2</option>
                    <option value="3">Product - 3</option>
                    <option value="4">Product - 4</option>
                    <option value="5">Product - 5</option>
                   </select>
                </div>
            </div>
           
            <div class="field email required">
                <label class="label" for="email">Email:-</label>
                <div class="control">
                    <input name="email" id="email"  class="input-text" type="email" data-validate="{required:true, 'validate-email':true}"/>
                </div>
            </div>  
                                 
    </fieldset>
    <div class="actions-toolbar">
        <div class="primary">
            <input type="hidden" name="hideit" id="hideit" value="" />
            <button type="submit" title="<?php echo __('Submit') ?>" class="action submit primary">
                <span><?php echo __('Submit') ?></span>
            </button>
        </div>
    </div>
</form>

步骤 6: 在以下路径创建电子邮件模板布局文件“email_templates.xml”

app/code/Vendor/Extension/etc

现在添加以下代码

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
     <template id="customemail_email_template" label="Email Form" file="customeremail.html" type="html" module="Vendor_Extension" area="frontend"/>
</config>

第 7 步:在下面的路径上创建一个电子邮件 html 文件“客户电子邮件.html”

app/code/Vendor/Extension/view/frontend/email

然后附加下面给出的代码

<body style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
    <div style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
    <table cellspacing="0" cellpadding="0" border="0" height="100%" width="100%">
        <tr>
            <tr>
                <td valign="top" colspan="5">
                    <p style="border:1px solid #E0E0E0; font-size:12px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9; text-align:center;"><strong>Product Information</strong></td>
                    </tr>
 
 <!-- Method- 1 -->
 
                {{depend name}}
                <tr>
                    <td>
                        <p style="border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;">product Id :-  {{var name}}  </p>
                    </td>
                </tr>
                {{/depend}}
 <!-- Method -  1 -->
 
 <!-- Method- 2 -->
                {{if email}}
                <tr>
                    <td>
                        <p style="border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;"> {{var email}} if condition</p>
                    </td>
                </tr>
                {{/if}}
 <!-- Method-  2-->
 
 <!-- Method- 3 -->
 
                {{block class='Magento\\Framework\\View\\Element\\Template' 
                area='frontend' template='Vendor_Extension::productinformation.phtml' name=$name}}
 
 <!-- Method- 3 -->                  
                </table>
            </td>
        </tr>
    </table>
    </div>
    </body>

步骤 8:在以下路径为条件值创建模板文件“productinformation.phtml”

app/code/Vendor/Extension/view/frontend/templates

最后,添加以下代码

<?php
 
switch ($this->getData('name'))
{
    case "0":
      echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> No Product Selected</p></td></tr>" ;
      break; 
    case "1":
        echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 1 Is Selected</p></td></tr>" ;
      echo "<p> </p>" ;
      break; 
    case "2":
        echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 2 Is Selected</p></td></tr>" ;
      break; 
    case "3":
        echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 3 Is Selected</p></td></tr>" ;
      break; 
    case "4":
        echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 4 Is Selected</p></td></tr>" ;
      break; 
    case "5":
        echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 5 Is Selected</p></td></tr>" ;
      break; 
    default:
    echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> No Record Found</p></td></tr>" ;  
}

结论:

通过实施上述步骤,您可以轻松地在Magento 2电子邮件模板中包含条件语句。


推荐文章