1

I am using Magento 2.2.3.

I tried "How to add new Shipping address form field in Checkout Page".Below is my code.

Vendor/Theme/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Atlantis_Everest',
    __DIR__
);

Vendor/Theme/etc/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\Checkout\Block\Onepage">
        <arguments>
            <argument name="layoutProcessors" xsi:type="array">
                <item name="rewrite-checkout-fields" xsi:type="object">Atlantis\Everest\Model\Checkout\LayoutProcessorPlugin</item>
            </argument>
        </arguments>
</type>
</config>

Vendor/Theme/etc/extension_attributes.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Quote\Api\Data\AddressInterface">
        <attribute code="custom_field" type="string" />
    </extension_attributes>
</config>

Vendor/Theme/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Atlantis_Everest" setup_version="1.0.0" />
</config>

Vendor/Theme/Model/Checkout/LayoutProcessorPlugin.php

<?php
$customAttributeCode = 'custom_field';
$customField = [
    'component' => 'Magento_Ui/js/form/element/abstract',
    'config' => [
        // customScope is used to group elements within a single form (e.g. they can be validated separately)
        'customScope' => 'shippingAddress.custom_attributes',
        'customEntry' => null,
        'template' => 'ui/form/field',
        'elementTmpl' => 'ui/form/element/input',
        'tooltip' => [
            'description' => 'this is what the field is for',
        ],
    ],
    'dataScope' => 'shippingAddress.custom_attributes' . '.' . $customAttributeCode,
    'label' => 'Custom Attribute',
    'provider' => 'checkoutProvider',
    'sortOrder' => 0,
    'validation' => [
       'required-entry' => true
    ],
    'options' => [],
    'filterBy' => null,
    'customEntry' => null,
    'visible' => true,
];

$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children'][$customAttributeCode] = $customField;

Vendor/Theme/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/action/set-shipping-information': {
                'Atlantis_Everest/js/action/set-shipping-information-mixin': true
            }
        }
    }
};

Vendor/Theme/view/frontend/web/js/action/set-shipping-information-mixin.js

/*jshint browser:true jquery:true*/
/*global alert*/
define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote'
], function ($, wrapper, quote) {
    'use strict';

    return function (setShippingInformationAction) {

        return wrapper.wrap(setShippingInformationAction, function (originalAction) {
            var shippingAddress = quote.shippingAddress();
            if (shippingAddress['extension_attributes'] === undefined) {
                shippingAddress['extension_attributes'] = {};
            }

            shippingAddress['extension_attributes']['custom_field'] = shippingAddress.customAttributes['custom_field'];
            // pass execution to original action ('Magento_Checkout/js/action/set-shipping-information')
            return originalAction();
        });
    };
});

I did not know how to perform Step 5 mentioned in the link.I performed till Step4. But When I deployed it,it does not show in Frontend. Please help me out. Thanks in advance.

2

2 Answers 2

0

try Clearing your static files and flushing your cache

you can do this through the backend or run

rm -rf pub/static && php-7.0 bin/magento cache:clean && php-7.0 bin/magento cache:flush

from your www/http folder from ssh

3
  • 1
    I have performed,sudo php magento setup:upgrade,sudo php magento setup:di:compile,sudo php magento setup:static-content:deploy –f,sudo php magento cache:flush,sudo chmod -R 777 var,sudo chmod -R 777 generated Oct 5, 2018 at 10:18
  • you shouldnt be running chmod -R 777 on all files. this is a major security risk. 777 gives all files Read, Write and Execute permissions and should not be set up this way at all. please revise what you are doing. If your code to add a new field is not working after doing what i said, then there is an issue in your code somewhere that needs rectifying
    – vmp
    Oct 5, 2018 at 10:23
  • 1
    It asked permission.So that only I run chmod for var and generated folders Oct 8, 2018 at 3:47
0

Try to follow below code to create customer address attribute for admin/frontend

1) create UpgradeData.php file(app/code/Vendor/CustomerAddressAttribute/Setup) in your existing module or create new module take reference from here

2) paste below code in your UpgradeData.php

namespace Vendor\CustomerAddressAttribute\Setup;

use Magento\Eav\Api\Data\AttributeSetInterfaceFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;

class UpgradeData implements UpgradeDataInterface
{
    /**
     * Customer setup factory
     *
     * @var CustomerSetupFactory
     */
    private $customerSetupFactory;

    /**
     * @var AttributeSetFactory
     */
    private $attributeSetFactory;

    /**
     * Init
     *
     * @param CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetInterfaceFactory $attributeSetFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory  = $attributeSetFactory;
    }

    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer_address');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSet     = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute('customer_address', 'district', [
            'type'             => 'varchar',
            'label'            => 'District',
            'input'            => 'text',
            'required'         => false,
            'visible'          => true,
            'visible_on_front' => true,
            'user_defined'     => false,
            'sort_order'       => 43,
            'position'         => 43,
            'system'           => 0,
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'district')
            ->addData([
                'attribute_set_id'   => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms'      => ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address', 'customer_address'],
            ]);
        $attribute->save();

        $setup->endSetup();
    }
}

3) run this command php bin/magento setup:upgrade && php bin/magento setup:static-content:deploy -f

4) go to admin side customer -> review any customer's address tab, you will see District field there, also you will see at checkout -> shipping address

10
  • Thank you @Hit's.But i need to store as attribute in Database.How can I achieve that? Oct 8, 2018 at 3:46
  • @VishaliMariappan see my updated answer, let me know if you have any query
    – Hitesh
    Oct 8, 2018 at 5:23
  • Okay.i will try this and inform you.Thank you for helping me Oct 8, 2018 at 5:25
  • When I added this UpgradeData.php,I faced the following errors.[ReflectionException] Class SR\CheckoutAdditionalField\Setup\CustomerSetupFactory does not exist [RuntimeException] Source class "\SR\CheckoutAdditionalField\Setup\CustomerSetup" for "SR\Chec koutAdditionalField\Setup\CustomerSetupFactory" generation does not exist. Oct 8, 2018 at 9:10
  • SR\CheckoutAdditionalField module is I think your custom module and when you run deploy command magento unable to find SR\CheckoutAdditionalField\Setup\CustomerSetupFactory class in your module. paste your effort in your question
    – Hitesh
    Oct 8, 2018 at 9:53

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.