To either make the State option MANDATORY or OPTIONAL, as of Magento 2.2.x, you set the option at: STORES>>Configuration>>General>>State Options
public function afterProcess(\Magento\Checkout\Block\Checkout\LayoutProcessor $subject, $result)
{
$districtAttributeCode = 'district_id';
$districtField = [
'component' => 'Vendor_Module/js/form/element/district',
'config' => [
'customScope' => 'shippingAddress',
'customEntry' => 'shippingAddress.district',
'template' => 'ui/form/field',
'elementTmpl' => 'ui/form/element/select',
],
'dataScope' => 'shippingAddress.district_id',
'provider' => 'checkoutProvider',
'filterBy' => [
'target' => '${ $.provider }:${ $.parentScope }.region_id',
'field' => 'region_id',
],
'customEntry' => 'shippingAddress.region_id'
];
$result['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children'][$districtAttributeCode] = $districtField;
return $result;
}
public function afterProcess(\Magento\Checkout\Block\Checkout\DirectoryDataProcessor $directoryDataProcessor, $jsLayout)
{
if (!isset($jsLayout['components']['checkoutProvider']['dictionaries']['district_id'])) {
$jsLayout['components']['checkoutProvider']['dictionaries']['district_id'] =
[
[
'value' => ’’,
'label' => ‘’,
'title' => ‘’,
‘region_id’ => ‘’,
],….
];
}
return $jsLayout;
}
enter code here
define([
'Magento_Ui/js/form/element/select'
], function ( Select) {
'use strict';
return Select.extend({
defaults: {
skipValidation: false,
imports: {
update: '${ $.parentName }.region_id:value',
initialOptions: "index =
checkoutProvider:dictionaries.district_id",
setOptions: "index = checkoutProvider:dictionaries.district_id"
}
},
});
});
Best Answer
Basically Magento takes the list of regions/states from its own database. If you look into Magento database you would find two tables named
directory_country_region
anddirectory_country_region_name
.directory_country_region
is for adding states/regions anddirectory_country_region_name
is for locale translations. By default Magento has regions only for few countries. If selected country has any region record in table then it appears as dropdown, else region area appears as input text.So if you want to show states dropdown for Nigeria you need to enter records into these tables through script/query. Put
country_id
as NG. Please refer https://mage2-blog.com/magento-add-regions-to-country/ to know more about inserting states through query.Hope it helps you.