Skip to main content
General

How to restrict specific US states in checkout – Magento 2

By |February 15, 2019 January 3rd, 2022No Comments

It’s mandatory for the online store to use the State/Province field in their system. But in some countries, there is no need to include a few states at the time of checkout.

In this article, I will show you how to restrict some US States in the checkout. For this, I have created a US State restriction selection drop-down in the admin panel system configuration. In the example below, you may find Dckap as Namespace and CustomerAddresses as ModuleName.

Step 1

Get our best content on eCommerce and backend operations to optimize your distribution business for profitability in your inbox one time a week.


We have to create a system configuration in the admin panel for getting the allowed US states for checkout. Create a system.xml file in the path below and the configuration will be displayed in Stores → Configuration → Sales → Checkout

Path: app/code/Dckap/CustomerAddresses/etc/adminhtml/system.xml

sales Magento_Checkout::checkout DckapCustomerAddressesModelConfigRegion RegionInformationProvider

First of all, we need to get the list of the allowed states, so we will need to gather such details from the MagentoDirectoryModelResourceModelRegionCollection. From this collection, we will be able to get the allowed country name, and by using the country details, we will get the states’ data, so we will have to override some files for collecting such information.

Path: app/code/Dckap/CustomerAddresses/etc/frontend/di.xml





      

           

      

Then we will have to update the US state list in that multi-select box form using below class.

DckapCustomerAddressesModelConfigRegionRegionInformationProvider

Path : DckapCustomerAddressesModelConfigRegionRegionInformationProvider

namespace DckapCustomerAddressesModelConfigRegion;

class RegionInformationProvider

{

  /**

   * @var MagentoDirectoryApiCountryInformationAcquirerInterface

   */

  protected $countryInformationAcquirer;

  protected $addressRepository;

  public function __construct(

      MagentoDirectoryApiCountryInformationAcquirerInterface $countryInformationAcquirer

  ) {

         $this->countryInformationAcquirer = $countryInformationAcquirer;

  }

  public function toOptionArray()

  {

        $countries = $this->countryInformationAcquirer->getCountriesInfo();

        foreach ($countries as $country) {

            // Get regions for this country:
 
            $regions = [];

            if ($availableRegions = $country->getAvailableRegions()) {

                 foreach ($availableRegions as $region) {

                      $regions[] = [

                         'value' => $region->getName(),

                         'label' => $region->getName()
   
                       ];

                 }

             }

        }

        return $regions;

     }

}

[POSTCTA]

Step 2

In Magento2 admin panel, go to Stores → Configuration from the left-side navigation panel. Then Goto General section → General → Country options → Choose ‘United States’ in Allowed Countries. Because we only list the allowed countries states in our custom system configuration field.

Magento 2 Checkout

And then select the US States from the Allowed US States in Checkout drop-down which you will want to display in the checkout form.

Magento 2 Checkout

Step 3

To get the chosen allowed US States for the checkout page by using the below set of code, we must override the MagentoDirectoryModelResourceModelRegionCollection for the checkout form State/Province drop down.

scopeConfig = $scopeConfig;

  }

  public function afterToOptionArray($subject, $options)

  {

      $allowedStates = $this->scopeConfig->getValue('checkout/state_filter/us_state_filter', MagentoStoreModelScopeInterface::SCOPE_STORE);

      $this->allowedUsStates = explode(",", $allowedStates);

      $result = array_filter($options, function ($option) {

          if (isset($option['label'])){

              return in_array($option['label'], $this->allowedUsStates);

          }

          return true;

      });

      return $result;

  }

}

Here,

$this->allowedUsStates => This variable has an array of allowed US state values.

$option => This variable has all the US states.

By using the above after function, we must compare both the state values and return the chosen state value, if that was present in the $option.

Step 4

Open your terminal and go to the Magento 2 root. Run from there with the following command:

php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:clean
php bin/magento cache:flush

Finally, the chosen states will show up in the checkout page state/province selection dropdown.

If you found this blog helpful, then please do let us know if you have any queries.

You can focus on achieving your business goals.
Still Wondering who will take care of Magento Support and Maintenance ?
The answer is “Us” – Get in touch! Let’s talk about how!

Rama Lekshmi

Author Rama Lekshmi

Rama Lekshmi enjoys solving complex problems and turning them into a simple and perfect coding structure. She is very fond of the logic and structure of coding and has always strived to write smart and efficient code, whether be it WordPress, CodeIgniter and Magento 2. When she isn't coding, she likes taking a tour all over India.

More posts by Rama Lekshmi

Discover What You’re Missing

Get the weekly email full of actionable ideas and insights you can use at work and home.