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();
    }
4
  • can you give code which you are using Nov 29, 2018 at 5:28
  • Please upload code or give file path where you want to get? Nov 29, 2018 at 5:48
  • I have a custom custroller and reading the country name from from a csv
    – Vindhuja
    Nov 29, 2018 at 5:52
  • Check my answer. Nov 29, 2018 at 6:23

1 Answer 1

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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