need to fetch country and state drop down in contact form in magento 2.4.3
it showcase & fetches state for default country but could not fetch any other selected country from drop down .
code for form.phtml
<?php
$countryList=$block->getCountries();
$regionList=$block->getRegion(); ?>
<form class="form retuns"
action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
id="return-form"
method="post"
data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
data-mage-init='{"validation":{}}'>
<div class="field country required">
<label class="label" for="country"><span><?php /* @escapeNotVerified */ echo __('Country') ?></span></label>
<div class="control">
<?php echo $countryList?>
</div>
</div>
<div class="field region required">
<label class="label" for="state"><span><?php /* @escapeNotVerified */ echo __('State') ?></span></label>
<div class="control">
<?php echo $regionList?>
</div>
</div>
<div class="field states required" style="display:none">
<label class="label" for="states"><span><?php /* @escapeNotVerified */ echo __('State') ?></span></label>
<div class="control">
<input name="state" id="states" title="<?php /* @escapeNotVerified */ echo __('State') ?>" class="input-text" type="text" />
</div>
</div>
</form>
<script>
require(['jquery', 'jquery/ui'], function(){
jQuery(document).on('change','#country',function() {
var param = 'country='+jQuery('#country').val();
jQuery.ajax({
showLoader: true,
url: '<?php /* @escapeNotVerified */ echo $block->getRegion(); ?>',
data: param,
type: "GET",
dataType: 'json'
}).success(function (data) {
alert(data.value);
if(data.value=='')
{
jQuery('.field.states.required').show();
jQuery('.field.region.required').hide();
}
else
{
jQuery('#state').append(data.value);
jQuery('.field.states.required').hide();
jQuery('.field.region.required').show();
}
}).error(function(data){
alert('blank');
});
});
});
</script>
code for contactForm.php
<?php
namespace Dcwilkinson\CustomContact\Block;
use Magento\Framework\View\Element\Template;
class ContactForm extends \Magento\Framework\View\Element\Template
{
protected $directoryBlock;
protected $_isScopePrivate;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Directory\Block\Data $directoryBlock,
array $data = []
)
{
parent::__construct($context, $data);
$this->_isScopePrivate = true;
$this->directoryBlock = $directoryBlock;
}
public function getCountries()
{
$country = $this->directoryBlock->getCountryHtmlSelect();
return $country;
}
public function getRegion()
{
$region = $this->directoryBlock->getRegionSelect();
return $region;
}
public function getCountryAction()
{
return $this->getUrl('contact', ['_secure' => true]);
}
}
Best Answer
heres the update try this solution it work for us https://magebug.blogspot.com/2018/04/magento-2-how-to-display-country.html