How To

Magento 2: Add Conditional Statement in Email Template

Hello Magento Friends,

Today we will discover How to Add Conditional Statement in Email Template in Magento 2. 

An email template is a predefined structure of email that includes text or images. Magento 2 admin can even add conditional statements in the email template to make it dynamic.

Let’s look at the steps to learn how to add conditional statement in Magento 2.

Steps to Add Conditional Statement in Email Template in Magento  2:

Step 1: Create blog file “Index.php” at the below path

app/code/Vendor/Extension/Block/Index

Then add the code as follows

<?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();
    }
}

Step 2: Create controller file “Index.php” at the below-mentioned path

app/code/Vendor/Extension/Controller/Index

Then add the following code-snippet

<?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();
    }
}

Step 3: Create controller file Post.php at the following path

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

Then add the following code snippet

<?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");
        }           
         
    }
}

Step 4: Create an “email_index_index.xml” file for the front side form display at the below path

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

Then add the below piece of code

<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>

Step 5: Create form template “form.phtml” at the below path

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

Now add the following fragment of code

<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>

Step 6: Create an email template layout file  “email_templates.xml” at the following path

app/code/Vendor/Extension/etc

Now add the following code

<?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>

Step 7: Create an email html file “customeremail.html” at the path underneath

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

Then append the code given below

<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>

Step 8: Create template file “productinformation.phtml” for conditional value at the below path

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

And finally, add the below code

<?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>" ;  
}

Conclusion:

By implementing the above steps, you can easily include conditional statements in Magento 2 email templates. Also, learn How to Customize Email Templates in Magento 2.

If you face any trouble, connect with me through the comment part and I will quickly help you find the solution.

Happy Coding!

Click to rate this post!
[Total: 3 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

5 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago