I want to create a select dropdown field in contact form(phtml file) which must be called dynamically in magento2.2.5?
Refer screenshot
This is my from I have override my contact form, I want a dropdown for Subject field.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI want to create a select dropdown field in contact form(phtml file) which must be called dynamically in magento2.2.5?
Refer screenshot
This is my from I have override my contact form, I want a dropdown for Subject field.
This is one of the ways to create a Dropdown (Select box) and get values dynamically inside phtml
<?php
$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 }} ?>
</select>
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">
<head>
<title>Contact Form</title>
</head>
<body>
<referenceContainer name="content">
<block class="Vendor\Module\Block\Contact" name="contact.form" template="Vendor_Module::form.phtml"/>
</referenceContainer>
</body>
</page>
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"/>
</referenceContainer>
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;
}