0

I need to display the all the USA states as a select drop-down in magento2 custom phtml. Can anyone help me.

0

Add following code in your block class

<?php
    ...

    private $directoryData;

    public function __construct(
        ...
        \Magento\Directory\Block\Data $directoryData
        ...
    ) {
        ...
        $this->directoryData = $directoryData;
        ...
    }

    public function getStates()
    {
        return $this->directoryData->getRegionHtmlSelect();
    }
}

Add following code in your PHTML file

<?php

echo $block->getStates();

Extra Notes:

You can use following code to get the complete data.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$states = $objectManager->create('Magento\Directory\Model\RegionFactory')
        ->create()->getCollection()->addFieldToFilter('country_id','US');
echo "<pre>";
print_r($states->getData());
0
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$regionFactory = $objectManager->create('Magento\Directory\Model\ResourceModel\Region\CollectionFactory')->create();
$regionFactory->addFieldToFilter('country_id', array('eq' => 'US'));
echo '<pre>';print_r($regionFactory->getData());

Also if you can directly call default magento country and state drop down in your custom phtml file, Here is link may be it's help full. https://magebug.blogspot.in/2018/04/magento-2-how-to-display-country.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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