Magento: Listing regions from a country code

Once and a while you may want to get a collection of the regions that are associated with a country in Magento. For example, the United States is of course a collection of… states. In Magento these are referred to as regions (Japan’s prefectures would hence be referred to as regions as well.)

So for a given country (and that country’s ID or country code) you might want to find all the regions in that country. Which are usually used to populate a dropdown menu on the address selection pages or shipping tax pages.


$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($this->getCountryId())
->load();

It’s great when ORM works for a developer. The problem with Magento I find is the complete lack of documentation. I only discovered the above technique after 20 minutes of grepping the app/code/core directory… :|

And remember to use Magento’s log method:


foreach($collection as $region) {

Mage::log(print_r($region, true));

}

Note some of the more useful attributes of that $region object are:

  • $region->default_name
  • $region->code

Which give responses along the lines of South Australia and SA, respectively.

Tags: ,

3 Responses to “Magento: Listing regions from a country code”

  1. Tester Says:

    Its a very helpful code snippet. Can you plz let me know that how would I get the country code or country id selected in shipping process ?

  2. TCMG Says:

    Hi,

    I’m actually sitting my university exams at the moment so I can’t really help you right now.

    After my exams I’ll take a crack at it for you though.

    Cheers

  3. Chrissy Clark Says:

    We have very helpful location for country code information. You can get a wide range of answers and stay current at countrycode.org

    Best regards,

    Chrissy

Leave a Reply