5

I need to limit area in checkout page. I need to set only one default option for the form field in checkout page.

country: India

state: Tamilnadu

City: Chennai

I can only achieve country from Admin Store->Configuration->General->General->Country Options. Remaining things not found in dropdown.

Please anyone suggest how to set default value of State and city.

9
  • we can achieve city wise or not, i am not sure about it. Is it possible for you to collect all chennai pin codes ? , than you can use table rate shipping method. Apr 15, 2016 at 9:31
  • for my case user only enter the pin code,address. I expect set default value of country,state,city remaining details get from user. @Baby in Magento Apr 15, 2016 at 9:38
  • you can remove the fields for "state" & "city" through code. Apr 15, 2016 at 10:09
  • sorry I can't get clear. mandatory or non mandatory is not a problem, how to set default value in those field is the only concern to me Apr 15, 2016 at 10:14
  • instead of setting default values , you can hide those fields, is that okay ? Apr 15, 2016 at 10:19

2 Answers 2

10

Here is way to set value & make field readonly(disabled)

Override vendor/magento/module-checkout/view/frontend/layout/checkout_index_index.xml to app/design/frontend/package/themename/Magento_Checkout/layout/checkout_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.root">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="checkout" xsi:type="array">
                            <item name="children" xsi:type="array">
                                <item name="steps" xsi:type="array">
                                    <item name="children" xsi:type="array">
                                        <item name="shipping-step" xsi:type="array">
                                            <item name="children" xsi:type="array">
                                                <item name="shippingAddress" xsi:type="array">
                                                    <item name="children" xsi:type="array">
                                                        <item name="shipping-address-fieldset" xsi:type="array">
                                                            <item name="children" xsi:type="array">
                                                                <item name="company" xsi:type="array">
                                                                    <item name="visible" xsi:type="boolean">false</item>
                                                                </item>
                                                                <item name="city" xsi:type="array">
                                                                    <item name="disabled" xsi:type="string">disabled</item>
                                                                    <item name="value" xsi:type="string">Value</item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

In above file i added,

<item name="company" xsi:type="array">
    <item name="visible" xsi:type="boolean">false</item>
</item>
<item name="city" xsi:type="array">
    <item name="disabled" xsi:type="string">disabled</item>
    <item name="value" xsi:type="string">value</item>
</item>

Then Override, \Magento\Checkout\Block\Checkout\AttributeMerger to Namespace\Modulename\Block\Checkout\AttributeMerger

/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Namespace\Modulename\Block\Checkout;

class AttributeMerger extends \Magento\Checkout\Block\Checkout\AttributeMerger
{
    public function __construct(
        \Magento\Customer\Helper\Address $addressHelper,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Directory\Helper\Data $directoryHelper
    ) {
        parent::__construct(
            $addressHelper,           
            $customerSession,
            $customerRepository,
            $directoryHelper
        );
    }

    /**
     * Retrieve UI field configuration for given attribute
     *
     * @param string $attributeCode
     * @param array $attributeConfig
     * @param array $additionalConfig field configuration provided via layout XML
     * @param string $providerName name of the storage container used by UI component
     * @param string $dataScopePrefix
     * @return array
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    protected function getFieldConfig(
        $attributeCode,
        array $attributeConfig,
        array $additionalConfig,
        $providerName,
        $dataScopePrefix
    ) {
        // street attribute is unique in terms of configuration, so it has its own configuration builder
        if (isset($attributeConfig['validation']['input_validation'])) {
            $validationRule = $attributeConfig['validation']['input_validation'];
            $attributeConfig['validation'][$this->inputValidationMap[$validationRule]] = true;
            unset($attributeConfig['validation']['input_validation']);
        }

        if ($attributeConfig['formElement'] == 'multiline') {
            return $this->getMultilineFieldConfig($attributeCode, $attributeConfig, $providerName, $dataScopePrefix);
        }

        $uiComponent = isset($this->formElementMap[$attributeConfig['formElement']])
            ? $this->formElementMap[$attributeConfig['formElement']]
            : 'Magento_Ui/js/form/element/abstract';
        $elementTemplate = isset($this->templateMap[$attributeConfig['formElement']])
            ? 'ui/form/element/' . $this->templateMap[$attributeConfig['formElement']]
            : 'ui/form/element/' . $attributeConfig['formElement'];

        $element = [
            'component' => isset($additionalConfig['component']) ? $additionalConfig['component'] : $uiComponent,
            'config' => [
                // customScope is used to group elements within a single form (e.g. they can be validated separately)
                'customScope' => $dataScopePrefix,
                'customEntry' => isset($additionalConfig['config']['customEntry'])
                    ? $additionalConfig['config']['customEntry']
                    : null,
                'template' => 'ui/form/field',
                'elementTmpl' => isset($additionalConfig['config']['elementTmpl'])
                    ? $additionalConfig['config']['elementTmpl']
                    : $elementTemplate,
                'tooltip' => isset($additionalConfig['config']['tooltip'])
                    ? $additionalConfig['config']['tooltip']
                    : null
            ],
            'dataScope' => $dataScopePrefix . '.' . $attributeCode,
            'label' => $attributeConfig['label'],
            'provider' => $providerName,
            'sortOrder' => isset($additionalConfig['sortOrder'])
                ? $additionalConfig['sortOrder']
                : $attributeConfig['sortOrder'],
            'validation' => $this->mergeConfigurationNode('validation', $additionalConfig, $attributeConfig),
            'options' => $this->getFieldOptions($attributeCode, $attributeConfig),
            'filterBy' => isset($additionalConfig['filterBy']) ? $additionalConfig['filterBy'] : null,
            'customEntry' => isset($additionalConfig['customEntry']) ? $additionalConfig['customEntry'] : null,
            'visible' => isset($additionalConfig['visible']) ? $additionalConfig['visible'] : true,
        ];

        if (isset($additionalConfig['disabled']) && $additionalConfig['disabled'] != null) {
             $element['disabled'] = "disabled";
        }

        if (isset($additionalConfig['value']) && $additionalConfig['value'] != null) {
             $element['value'] = "";
        }

        if (isset($attributeConfig['value']) && $attributeConfig['value'] != null) {
            $element['value'] = $attributeConfig['value'];
        } elseif (isset($attributeConfig['default']) && $attributeConfig['default'] != null) {
            $element['value'] = $attributeConfig['default'];
        } else {
            $defaultValue = $this->getDefaultValue($attributeCode);
            if (null !== $defaultValue) {
                $element['value'] = $defaultValue;
            }

        }

        return $element;
    }

    /**
     * @param string $attributeCode
     * @return null|string
     */
    protected function getDefaultValue($attributeCode)
    {
        switch ($attributeCode) {
            case 'firstname':
                if ($this->getCustomer()) {
                    return $this->getCustomer()->getFirstname();
                }
                break;
            case 'lastname':
                if ($this->getCustomer()) {
                    return $this->getCustomer()->getLastname();
                }
                break;
            case 'country_id':
                return $this->directoryHelper->getDefaultCountry();
                break;
            case 'city':
                if ($this->getCustomer()) {
                    return "return your value"
                }
        }
        return null;
    }


}

In Above file i added below code in function getFieldConfig

if (isset($additionalConfig['disabled']) && $additionalConfig['disabled'] != null) {
    $element['disabled'] = "disabled";
}

And added below code in function getDefaultValue


case 'city':
    if ($this->getCustomer()) {
         return "return your value";
    }

Thanks !!

3
  • I will be back to you Jun 24, 2016 at 4:01
  • ok sure bilal :)
    – Narayan S
    Jun 24, 2016 at 9:21
  • it worked! :-) +1 Jul 2, 2016 at 9:40
4

Finally I have maken one solution by using Jquery.

require([ 'jquery', 'jquery/ui'], function($){

    setInterval(function () {

        if($('input[name="city"]').val() != 'Chennai')
        {

           $('input[name="city"]').val("Chennai");
           $('input[name="city"]').attr('readonly',true);
           $('input[name="city"]').trigger('keyup');
           $('input[name="region"]').val("Tamilnadu");
           $('input[name="region"]').attr('readonly',true);
           $('input[name="region"]').trigger('keyup');

        }

        },3000);

});

In above code kindly note it after change field value I can use keyup event. Because in checkout page update the value in database after keyup event only, so I am using keyup event to update my changed value in DB. Also give readonly for none of one change my field.

note: I am not sure this is the right way to done this, but Its solidly work for me :-)

one more thing I hardly try to do in magento way but everything got failed so someone have idea to how to done this by magento way post your answer after verifying tick your answer. I'm eagerly waiting :-)

1
  • 2
    in which file you added this Jquery?
    – Mujahidh
    Jan 23, 2020 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.