magento 2 state dropdown from custom table in address form
-
26-12-2020 - |
Question
I want to show state drop-down in checkout address form.
state options will be come from my custom table. not from directory_country_region_name
.
Solution
After lot of search finally i got solution:
Vendor/Module/registration.php
& put below code.
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vendor_Module',
__DIR__
);
add the module.xml file in Vendor/Module/etc/module.xml
& put below code.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Vendor_Module" setup_version="1.0.0"></module>
</config>
add the InstallSchema.php file in Vendor/Module/Setup/InstallSchema.php
& put below code.
<?php
namespace Vendor\Module\Setup;
class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface {
/**
* install table
*
* @param \Magento\Framework\Setup\SchemaInterface $setup
* @param \Magento\Framework\Setup\ModuleContextInterface $context
* @return void
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*
*/
public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
/*State Table */
if (!$installer->tableExists('state')) {
$table = $installer->getConnection()->newTable(
$installer->getTable('state')
)
->addColumn(
'state_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'identity' =>true,
'nullable' =>false,
'primary' =>true,
'unsinged' =>true,
],
'state Id'
)
->addColumn(
'state_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[ 'nullable =>false'],
'State Code'
)
->addColumn(
'name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[ 'nullable =>false'],
'Name'
)
->addColumn(
'country_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[ 'nullable =>false'],
'Country Code'
)
->setComment('state Table');
$installer->getConnection()->createTable($table);
$installer->getConnection()->addIndex(
$installer->getTable('state'),
$setup->getIdxName(
$installer->getTable('state'),
['state_id','state_code','name','country_code'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
),
['state_id','state_code','name','country_code'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
);
}
$installer->endSetup();
}
}
In Block Vendor/Module/Block/Checkout/LayoutProcessor.php
put below code.
<?php
namespace Vendor\Module\Block\Checkout;
use Magento\Directory\Helper\Data as DirectoryHelper;
/**
* Class LayoutProcessor
* @package Vendor\Module\Block\Checkout
*/
class LayoutProcessor implements \Magento\Checkout\Block\Checkout\LayoutProcessorInterface
{
/**
* @var DirectoryHelper
*/
protected $directoryHelper;
/***
* State Option
*
* @var Vendor\Module\Model\Source\Stateoptions
*/
protected $_stateOption;
/**
* LayoutProcessor constructor.
* @param DirectoryHelper $directoryHelper
* @param \Vendor\Module\Model\Stateoptions $stateOptions
*/
public function __construct(
\Vendor\Module\Model\Source\Stateoptions $stateOption,
DirectoryHelper $directoryHelper
) {
$this->directoryHelper = $directoryHelper;
$this->_stateOption = $stateOption;
}
/**
* @param array $result
* @return array
*/
public function process($result)
{
if ($result['components']['checkout']['children']['steps']
['children']['shipping-step']['children']['shippingAddress'])
{
$shippingAddressFieldSet = $result['components']['checkout']['children']['steps']
['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children'];
region = $this->_stateOption->getStates();
$regionOptions[] = ['label' => 'Please Select..', 'value' => ''];
foreach ($region as $field) {
$regionOptions[] = ['label' => $field['name'], 'value' => $field['name']];
}
$shippingAddressFieldSet['region_id'] = '';
$shippingAddressFieldSet['region'] = '';
result['components']['checkout']['children']['steps']
['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children'] = $shippingAddressFieldSet;
$result['components']['checkout']['children']['steps']
['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['region'] = [
'component' => 'Magento_Ui/js/form/element/select',
'config' => [
'customScope' => 'shippingAddress',
'template' => 'ui/form/field',
'elementTmpl' => 'ui/form/element/select',
'id' => 'drop-down',
'additionalClasses' => 'state-drop-down',
],
'dataScope' => 'shippingAddress.region',
'label' => 'Province',
'provider' => 'checkoutProvider',
'visible' => true,
'validation' => [],
'sortOrder' => 115,
'id' => 'state-drop-down',
'options' => $regionOptions
];
}
return $result;
}
}
In Model Vendor/Module/Model/Source/Stateoptions.php
put below code.
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Vendor\Module\Model\Source;
/**
* @api
* @since 100.0.2
*/
class Stateoptions implements \Magento\Framework\Option\ArrayInterface
{
public function __construct(
\Magento\Framework\App\ResourceConnection $resource
) {
$this->_resource = $resource;
}
/**
* Options getter
*
* @return array
*/
public function toOptionArray()
{
$optionArray = [];
foreach ($this->getStates() as $field) {
$options[] = ['label' => $field['name'], 'value' => $field['state_id']];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [0 => __('No'), 1 => __('Yes')];
}
public function getStates()
{
$adapter = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
$select = $adapter->select()
->from('state');
return $adapter->fetchAll($select);
}
}
In etc Vendor/Module/etc/frontend/di.xml
put below code.
<?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\Checkout\Block\Onepage">
<arguments>
<argument name="layoutProcessors" xsi:type="array">
<item name="vendor_area_layoutprocessor" xsi:type="object">Vendor\Module\Block\Checkout\LayoutProcessor</item>
</argument>
</arguments>
</type>
</config>
This will shows state drop down from custom table(state) in shipping address form in checkout
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange