I want to create a select dropdown field in contact form(phtml file) which must be called dynamically in magento2.2.5?

Refer screenshot

enter image description here

This is my from I have override my contact form, I want a dropdown for Subject field.

  • What do you mean by calling dynamically ? Mar 6, 2019 at 7:09

1 Answer 1


This is one of the ways to create a Dropdown (Select box) and get values dynamically inside phtml

    $states     = $block->getStates();
<select name='order_items[state][]' class='form-control'>
 <?php foreach($states as $option) {
        if($option['value'] == '')
          { ?>
            <option value="">Please select State of Vehicle Registration</option>
    <?php } else{ ?>
            <option value="<?php echo $option['value'] ?>"><?php echo $option['label'] ?></option>
<?php }} ?>

Here you can see, the Dropdown values are fetched from the template's Block class using $block->getStates()

You can define template block class by creating a layout xml file inside like app\code\Vendor\Module\view\frontend\layout\contact_index_index.xml

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <title>Contact Form</title>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\Contact" name="contact.form" template="Vendor_Module::form.phtml"/>

Above you can see following section is responsible to define template's block class. So if you already have layout xml file for the form, then you can add below section to that layout xml file

<referenceContainer name="content">
     <block class="Vendor\Module\Block\Contact" name="contact.form" template="Vendor_Module::form.phtml"/>

Now inside your Block class app\code\Vendor\Module\Block\Contact.php

You can define your methods. And all the methods can be accessed from phtml using $block-><methodname>()

Example method in Contact.php block class

public function getStates()
    $options[0] =  ['value' => 'CA', 'label' => 'California'];
    $options[1] =  ['value' => 'AZ', 'label' => 'Arizona'];
    return $options;
  • Was this answer helpful? @Amy Sep 7, 2020 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.