12

How can I programmatically get the region_id in Magento from a 2-character state abbreviation? I'm using Magento 1.4.2 if that matters at all.

3 Answers 3

29
$regionModel = Mage::getModel('directory/region')->loadByCode($regionCode, $countryCode);
$regionId = $regionModel->getId();
1
  • And you can always loadByName if you need to! Name being like 'Texas'. Oct 9, 2018 at 19:43
1

Get the collection of all the states/regions related to specific country.

/**
 * Get region collection
 * @param string $countryCode
 * @return array
 */
public function getRegionCollection($countryCode)
{
    $regionCollection = Mage::getModel('directory/region_api')->items($countryCode);
    return $regionCollection;
}

Populate region list with region collection. Country code (e.g. NL, NP, EN) is passed as parameter to getRegionCollection function.

$regionCollection = $this->getRegionCollection($countryCode);

<select name='customer[region]' id='customer:region' class="validate-select" >
    <option>Please select region, state or province</option>
    <?php
        foreach($regionCollection as $region) {
            ?>
            <option value="<?php echo $region['name'] ?>" ><?php echo $region['name'] ?></option>
            <?php
        }
    ?>

</select> 
0

This is worked for me.

<div class="field">
                    <label for="region_id" class="required"><em>*</em><?php echo $this->__('State/Province') ?></label>
                    <div class="input-box">
                        <select id="region_id" name="region_id" title="<?php echo $this->__('State/Province') ?>" class="validate-select">
                            <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
                        <?php                        
                        $regions = Mage::getModel('directory/country')->load('US')->getRegions();
                        foreach($regions as $region)
                        {
                            echo "<option value=$region[name]>".$region['name'] . "</option>";
                        }
                        ?>

                    </select>                       

                    </div>
                </div>

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.