today we discuss about the, Magento 2 allow Country on checkout.
This article helps to store owners to restrict countries to place order by the customer is restricted in some countries.
Display only the countries you ship to on checkout in magento2.
Method 1
- Log in to the Magento admin panel and navigate to Stores > Configuration
- Select General under the General section.
- Expand Country Options
Method 2
Create di.xml file
app/code/Vendor/Mymodule/etc/di.xml
<?xml version="1.0" ?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <!-- country on the checkout page --> <type name="Magento\Checkout\Block\Checkout\DirectoryDataProcessor"> <plugin name="country_list_on_checkout" type="Vendor\Mymodule\Plugin\Block\Checkout\DirectoryDataProcessor" sortOrder="1"/> </type> </config>
Create DirectoryDataProcessor.php file
app/code/Vendor/Mymodule/Plugin/Block/Checkout/DirectoryDataProcessor.php
use Magento\Directory\Helper\Data as DirectoryHelper; use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Api\StoreResolverInterface; use Magento\Framework\App\ObjectManager; class DirectoryDataProcessor { public $scopeConfig; public function __construct( \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollection, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, StoreManagerInterface $storeManager = null ) { $this->countryCollectionFactory = $countryCollection; $this->scopeConfig = $scopeConfig; $this->storeManager = $storeManager ?: ObjectManager::getInstance()->get(StoreManagerInterface::class); } /** * @param BaseDirectoryDataProcessor $subject * @param $jsLayout * @return mixed */ public function afterProcess( BaseDirectoryDataProcessor $subject, $jsLayout ) { $countryOptions = $this->countryCollectionFactory->create()->loadByStore( $this->storeManager->getStore()->getId())->toOptionArray(); $valueFromConfig = $this->scopeConfig->getValue('general/country/allow', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); $allowcount = explode(',', $valueFromConfig); $finalCountries = []; $finalCountries[] = [ 'value' => '', 'label' => '' ]; foreach ($countryOptions as $key => $_country) { if($_country['value']){ $c_code = $_country['value']; if(in_array($c_code,$allowcount)){ $finalCountries[] = $_country; } } } /* $finalCountries = []; $finalCountries[] = [ 'value' => 'US', 'label' => 'United States', 'is_region_visible' => 1, 'is_default' => 1 ]; */ $jsLayout['components']['checkoutProvider']['dictionaries']['country_id'] = $finalCountries; return $jsLayout; } }