2

I have the country name with me. How can I get corresponding country code from it. For ex: If the country name is Unites States, I want to get country code from it ie, US

If there any way for it?

I found many useful links for getting country name from country code. I want it in the reverse manner.

   public function __construct(
            \Magento\Directory\Model\CountryFactory $countryFactory
        ) {
            $this->_countryFactory = $countryFactory;
        }

    public function getCountryname($countryCode){    
        $country = $this->_countryFactory->create()->loadByCode($countryCode)
        echo $country->getName();
    }
  • can you give code which you are using – Adarsh Shukla Nov 29 '18 at 5:28
  • Please upload code or give file path where you want to get? – Rohan Hapani Nov 29 '18 at 5:48
  • I have a custom custroller and reading the country name from from a csv – Vindhuja Nov 29 '18 at 5:52
  • Check my answer. – Rohan Hapani Nov 29 '18 at 6:23
2

You forgot to add semicolon after $country = $this->_countryFactory->create()->loadByCode($countryCode)

Add code in your controller :

protected $_country;

public function __construct(
    \Magento\Directory\Model\Country $country
) {
    $this->_country = $country;
}

public function getCountryname() {
    $countryName = "Your country name";
    $countryCollection = $this->_country->getCollection();
    foreach ($countryCollection as $country) {
       if ($countryName == $country->getName()) {
          $countryId = $country->getCountryId();
          break;
       }
    }
    echo $countryId;
}

remove generated folder and clean cache.

| improve this answer | |
  • I want to get country code from country name. Please read my question carefully. – Vindhuja Nov 29 '18 at 6:24
  • Sorry. My mistake. I update answer right now. – Rohan Hapani Nov 29 '18 at 6:25
  • Check it now... – Rohan Hapani Nov 29 '18 at 6:31
  • 1
    Please accept answer so it will helpful for other developer also :) – Rohan Hapani Nov 29 '18 at 7:07
  • Happy to help !! Happy Coding :) – Rohan Hapani Nov 29 '18 at 7:07

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.