Magento – Allow single county gives empty drop down options in front-end checkout Country field in Magento 2

checkoutcountry-regionsmagento2

We have configured Allow Countries to Canada in admin. On fronted, by default the checkout page country field is loading with Canada, but if we click on country drop down, empty drop-down fields are displaying.

Reference code.

<option value=""> </option>
<option data-title="" value=""></option>
<option data-title="Canada" value="CA">Canada</option>

Reference image.
enter image description here

Can any one help us on restricting country field to only one country instead of displaying empty or please select value options, so that allowed country can be one country by default and country field is non-select.

Best Answer

You can create the after plugin , this logic is work fine for me , to remove blank option from the country dropdown

1) create di.xml file in app/code/Mymodule/Custom/etc/frontend/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">
        <type name="Magento\Directory\Model\ResourceModel\Country\Collection">
            <plugin name="remove-empty-space" 
                type="Mymodule\Custom\Plugin\Country\Collection"/>
        </type>
    </config>

2 ) create plugin in the app/code/Mymodule/Custom/Custom/Plugin/Country/Collection.php

class Collection
{
    /**
     * Arguments processing.
     *
     * @param \Magento\Directory\Model\ResourceModel\Country\Collection $subject
     * @param $options
     * @return array|bool
     *
     */
    public function afterToOptionArray(
        \Magento\Directory\Model\ResourceModel\Country\Collection $subject,
        $options
    ) {
        $result = array_filter($options, function ($option) {
            return empty($option['value']) ? false : true;
        });
        return $result;
    }
}