Shuvankar Paul Software Engineer, Strativ AB Magento eCommerce Website Development, Website Development Using Php and HTML and Cross-Platform application development using Appcelerator.

Getting Country from Country Code in Magento 2

1 min read

In Magento 2 you can easily get Country Name from Directory

There are many way for example factory method, model method by directly from object Manager.

I may wrong, but by Interface seems comfortable & secure.

Interface Path – Magento\Directory\Api\CountryInformationAcquirerInterface;

In the below example, on one of my work i need to print pdf on a custom way, that’s way i need the billing address country and the shipping address country but, from sales order data i get it on as country id like “SE” (for Sweden)

in the method you can value in two way on method getCountryName(), in english or in local.

<?php

namespace Equaltrue\Orderprint\Block\Order;

use Magento\Backend\Block\Template\Context;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Directory\Api\CountryInformationAcquirerInterface;

class Print extends Template
{
    protected $_coreRegistry;
    protected $orderRepository;
    protected $countryInformationAcquirerInterface;

    /**
     * Constructor
     *
     * @param CountryInformationAcquirerInterface $countryInformationAcquirerInterface
     * @param OrderRepositoryInterface $orderRepository
     * @param Context $context
     * @param Registry $coreRegistry
     * @param array $data
     */
    public function __construct(
        CountryInformationAcquirerInterface $countryInformationAcquirerInterface,
        OrderRepositoryInterface $orderRepository,
        Context $context,
        Registry $coreRegistry,
        array $data = []
    ) {
        $this->orderRepository = $orderRepository;
        $this->countryInformationAcquirerInterface = $countryInformationAcquirerInterface;
        $this->_coreRegistry = $coreRegistry;
        parent::__construct($context, $data);
    }

    /**
     * Retrieve Current Data
     */
    public function getOrderData()
    {
        $orderId = $this->getRequest()->getParam('order_id', 0);
        $order =  $this->getOrder($orderId);

        /*
         * Get billing Address
         * */
        $billingAddress = $order->getBillingAddress();
        $firstNameBilling = $billingAddress->getFirstName();
        $lastNameBilling = $billingAddress->getLastName();
        $streetBilling = implode( ", ", $billingAddress->getStreet());
        $cityBilling = $billingAddress->getCity();
        $postCodeBilling = $billingAddress->getPostCode();
        $countryIdBilling = $billingAddress->getCountryId();
        $countryNameBilling = $this->getCountryName($countryIdBilling);
        $telephoneBilling = "T: ".$billingAddress->getTelephone();
        $formattedBillingAddress = $firstNameBilling." ".$lastNameBilling."<br>". $streetBilling."<br>". $cityBilling.",".$postCodeBilling."<br>".$countryNameBilling."<br>".$telephoneBilling;

        /*
         * Get billing Address
         * */
        $shippingAddress = $order->getShippingAddress();
        $firstNameShipping = $shippingAddress->getFirstName();
        $lastNameShipping = $shippingAddress->getLastName();
        $streetShipping = implode( ", ", $shippingAddress->getStreet());
        $cityShipping = $shippingAddress->getCity();
        $postCodeShipping = $shippingAddress->getPostCode();
        $countryIdShipping = $billingAddress->getCountryId();
        $countryNameShipping = $this->getCountryName($countryIdShipping);
        $telephoneShipping = "T: ".$shippingAddress->getTelephone();
        $formattedShippingAddress = $firstNameShipping." ".$lastNameShipping."<br>". $streetShipping."<br>". $cityShipping.",".$postCodeShipping."<br>".$countryNameShipping."<br>".$telephoneShipping;

        return array(
            "formatted_billing_address" => $formattedBillingAddress,
            "formatted_shipping_address" => $formattedShippingAddress
        );
    }

    /**
     * Getting Country Name
     * @param string $countryCode
     * @param string $type
     *
     * @return null|string
     * */
    public function getCountryName($countryCode, $type="local"){
        $countryName = null;
        try {
            $data = $this->countryInformationAcquirerInterface->getCountryInfo($countryCode);
            if($type == "local"){
                $countryName = $data->getFullNameLocale();
            }else {
                $countryName = $data->getFullNameLocale();
            }
        } catch (NoSuchEntityException $e) {}
        return $countryName;
    }

    protected function getOrder($id)
    {
        return $this->orderRepository->get($id);
    }
}

Thanks for the visit, please leave me a message at shuvoenr@gmail.com, if the solution is wrong or not working.

Shuvankar Paul Software Engineer, Strativ AB Magento eCommerce Website Development, Website Development Using Php and HTML and Cross-Platform application development using Appcelerator.

Some Manual Query in Magento 2

Change Product ID Magento 2 Change Magento 2 is on Manu Bulk
Shuvankar Paul
8 sec read

A Cook Book of Magento 2 Xml

Magento 2 Xml used Locations Configuration Files All those xml are used in component etc folder module.xml – Module Declaration events.xml – Modules Event...
Shuvankar Paul
8 sec read

Some Necessary MySQL task you need to know

Cloning a MySQL database to Another DB For details official documentation Copying MySQL Databases First you need to create a DB where the clone...
Shuvankar Paul
29 sec read

Leave a Reply

Your email address will not be published. Required fields are marked *