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

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

2 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

5 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 week ago

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

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 week ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

1 week ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago