Magento 2 : Add extra text field in checkout billing address and save it in orderMagento 2 checkout form: how to add custom field?How to add custom attribute in BILLING address in Magento 2Default Billing Address not saved when user having no address and do checkout In Magento 2Magento 2 add custom field in customer billing and shipping formHow to bind custom field to billing address Magento 2Magento 2 : How to Add address attribute in billing address form and convert that value in order addressHow to add new field in billing address in magento 2 and how to save that attribute data?Checkout billing address update custom attributesMagento 2 how to add extra validation to new Billing address form fields in checkout pageNew Checkout Billing Address Form Field not saving value to the databaseHow to add new custom field in checkout/shipping page and save it in db in Magento2.2.5?

Players of unusual orchestral instruments

Dropping outliers based on "2.5 times the RMSE"

Occasus nescius

Do native speakers use ZVE or CPU?

What does "Fotze" really mean?

How can an advanced civilization forget how to manufacture its technology?

What is this welding tool I found in my attic?

Is Arc Length always irrational between two rational points?

Too many spies!

To accent or not to accent in Greek

Is this floating-point optimization allowed?

How do Windows version numbers work?

How can I legally visit the United States Minor Outlying Islands in the Pacific?

Why would an Inquisitive rogue choose to use Insightful Fighting as opposed to using their Cunning Action to Hide?

How to repair a laptop's screen hinges?

Cubic programming and beyond?

School House Points (Python + SQLite)

Are local nested functions possible in elisp?

TikZ Can I draw an arrow by specifying the initial point, direction, and length?

How does one stock fund's charge of 1% more in operating expenses than another fund lower expected returns by 10%?

Why would guns not work in the dungeon?

In which ways do anagamis still experience ignorance?

Extract an attribute value from XML

I quit, and boss offered me 3 month "grace period" where I could still come back



Magento 2 : Add extra text field in checkout billing address and save it in order


Magento 2 checkout form: how to add custom field?How to add custom attribute in BILLING address in Magento 2Default Billing Address not saved when user having no address and do checkout In Magento 2Magento 2 add custom field in customer billing and shipping formHow to bind custom field to billing address Magento 2Magento 2 : How to Add address attribute in billing address form and convert that value in order addressHow to add new field in billing address in magento 2 and how to save that attribute data?Checkout billing address update custom attributesMagento 2 how to add extra validation to new Billing address form fields in checkout pageNew Checkout Billing Address Form Field not saving value to the databaseHow to add new custom field in checkout/shipping page and save it in db in Magento2.2.5?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I want to add one extra text field in checkout billing form and also save that field data in order so I can show that field data in admin order view and also in order email.



I already tried to add in shipping and it works properly but I want to add in billing.



Please help me.










share|improve this question






















  • refer this thread magento.stackexchange.com/questions/91867/…

    – Bojjaiah
    Sep 26 '17 at 5:51











  • I already tried this one but it added in the shipping address and I want an extra field in the billing address.

    – Sneha Panchal
    Sep 26 '17 at 5:53

















1















I want to add one extra text field in checkout billing form and also save that field data in order so I can show that field data in admin order view and also in order email.



I already tried to add in shipping and it works properly but I want to add in billing.



Please help me.










share|improve this question






















  • refer this thread magento.stackexchange.com/questions/91867/…

    – Bojjaiah
    Sep 26 '17 at 5:51











  • I already tried this one but it added in the shipping address and I want an extra field in the billing address.

    – Sneha Panchal
    Sep 26 '17 at 5:53













1












1








1








I want to add one extra text field in checkout billing form and also save that field data in order so I can show that field data in admin order view and also in order email.



I already tried to add in shipping and it works properly but I want to add in billing.



Please help me.










share|improve this question














I want to add one extra text field in checkout billing form and also save that field data in order so I can show that field data in admin order view and also in order email.



I already tried to add in shipping and it works properly but I want to add in billing.



Please help me.







magento2 checkout email billing-address input






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Sep 26 '17 at 5:49









Sneha PanchalSneha Panchal

5454 silver badges26 bronze badges




5454 silver badges26 bronze badges












  • refer this thread magento.stackexchange.com/questions/91867/…

    – Bojjaiah
    Sep 26 '17 at 5:51











  • I already tried this one but it added in the shipping address and I want an extra field in the billing address.

    – Sneha Panchal
    Sep 26 '17 at 5:53

















  • refer this thread magento.stackexchange.com/questions/91867/…

    – Bojjaiah
    Sep 26 '17 at 5:51











  • I already tried this one but it added in the shipping address and I want an extra field in the billing address.

    – Sneha Panchal
    Sep 26 '17 at 5:53
















refer this thread magento.stackexchange.com/questions/91867/…

– Bojjaiah
Sep 26 '17 at 5:51





refer this thread magento.stackexchange.com/questions/91867/…

– Bojjaiah
Sep 26 '17 at 5:51













I already tried this one but it added in the shipping address and I want an extra field in the billing address.

– Sneha Panchal
Sep 26 '17 at 5:53





I already tried this one but it added in the shipping address and I want an extra field in the billing address.

– Sneha Panchal
Sep 26 '17 at 5:53










1 Answer
1






active

oldest

votes


















0














Step 1: Create File: Adamsmage/Checkoutattribute/Setup/InstallData.php



<?php
namespace AdamsmageCheckoutattributeSetup;

use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;

class InstallData implements InstallDataInterface


private $customerSetupFactory;

/**
* Constructor
*
* @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory
)
$this->customerSetupFactory = $customerSetupFactory;


/**
* @inheritdoc
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

$customerSetup->addAttribute('customer_address', 'example', [
'label' => 'example',
'input' => 'text',
'type' => 'varchar',
'source' => '',
'required' => false,
'position' => 333,
'visible' => true,
'system' => false,
'is_used_in_grid' => false,
'is_visible_in_grid' => false,
'is_filterable_in_grid' => false,
'is_searchable_in_grid' => false,
'backend' => ''
]);


$attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'example')
->addData(['used_in_forms' => [
'customer_address_edit',
'customer_register_address'
]]);
$attribute->save();

$installer->getConnection()->addColumn(
$installer->getTable('quote_address'),
'example',
[
'type' => 'varchar',
'length' => 255
]
);

$installer->getConnection()->addColumn(
$installer->getTable('sales_order_address'),
'example',
[
'type' => 'varchar',
'length' => 255
]
);




Step 2: Create File: Adamsmage/Checkoutattribute/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="MagentoCustomerApiDataAddressInterface">
<attribute code="example" type="string"/>
</extension_attributes>
</config>


Step 3: Create File: Adamsmage/Checkoutattribute/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="MagentoCheckoutBlockOnepage">
<arguments>
<argument name="layoutProcessors" xsi:type="array">
<item name="adamsmage_extra_checkout_address_fields_layoutprocessor" xsi:type="object">AdamsmageCheckoutattributeBlockCheckoutLayoutProcessor</item>
</argument>
</arguments>
</type>
</config>


Step4 : Create File: Adamsmage/Checkoutattribute/Block/Checkout/LayoutProcessor.php



<?php

namespace AdamsmageCheckoutattributeBlockCheckout;

class LayoutProcessor implements MagentoCheckoutBlockCheckoutLayoutProcessorInterface
{

public function process($result)
$result = $this->getShippingFormFields($result);
$result = $this->getBillingFormFields($result);
return $result;


public function getAdditionalFields($addressType='shipping')
if($addressType=='shipping')
return ['example'];

return ['example'];


public function getShippingFormFields($result)
if(isset($result['components']['checkout']['children']['steps']['children']
['shipping-step']['children']['shippingAddress']['children']
['shipping-address-fieldset'])
)

$shippingPostcodeFields = $this->getFields('shippingAddress.custom_attributes','shipping');

$shippingFields = $result['components']['checkout']['children']['steps']['children']
['shipping-step']['children']['shippingAddress']['children']
['shipping-address-fieldset']['children'];

if(isset($shippingFields['street']))
unset($shippingFields['street']['children'][1]['validation']);
unset($shippingFields['street']['children'][2]['validation']);


$shippingFields = array_replace_recursive($shippingFields,$shippingPostcodeFields);

$result['components']['checkout']['children']['steps']['children']
['shipping-step']['children']['shippingAddress']['children']
['shipping-address-fieldset']['children'] = $shippingFields;



return $result;


public function getBillingFormFields($result)
if(isset($result['components']['checkout']['children']['steps']['children']
['billing-step']['children']['payment']['children']
['payments-list']))

$paymentForms = $result['components']['checkout']['children']['steps']['children']
['billing-step']['children']['payment']['children']
['payments-list']['children'];

foreach ($paymentForms as $paymentMethodForm => $paymentMethodValue)

$paymentMethodCode = str_replace('-form', '', $paymentMethodForm);

if (!isset($result['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children'][$paymentMethodCode . '-form']))
continue;


$billingFields = $result['components']['checkout']['children']['steps']['children']
['billing-step']['children']['payment']['children']
['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'];

$billingPostcodeFields = $this->getFields('billingAddress' . $paymentMethodCode . '.custom_attributes','billing');

$billingFields = array_replace_recursive($billingFields, $billingPostcodeFields);

$result['components']['checkout']['children']['steps']['children']
['billing-step']['children']['payment']['children']
['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'] = $billingFields;



return $result;


public function getFields($scope,$addressType)
$fields = [];
foreach($this->getAdditionalFields($addressType) as $field)
$fields[$field] = $this->getField($field,$scope);

return $fields;


public function getField($attributeCode,$scope)
$field = [
'config' => [
'customScope' => $scope,
],
'dataScope' => $scope . '.'.$attributeCode,
];

return $field;



Step5 : Modify file: Adamsmage/Checkoutattribute/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="Adamsmage_Checkoutattribute" setup_version="1.0.0">
<sequence>
<module name="Magento_Checkout"/>
</sequence>
</module>
</config>


Step6 : Create file: Adamsmage/Checkoutattribute/view/frontend/requirejs-config.js



var config = 
config:
mixins:
'Magento_Checkout/js/action/set-billing-address':
'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
,
'Magento_Checkout/js/action/set-shipping-information':
'Adamsmage_Checkoutattribute/js/action/set-shipping-information-mixin': true
,
'Magento_Checkout/js/action/create-shipping-address':
'Adamsmage_Checkoutattribute/js/action/create-shipping-address-mixin': true
,
'Magento_Checkout/js/action/place-order':
'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
,
'Magento_Checkout/js/action/create-billing-address':
'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true



;


Step7 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/create-shipping-address-mixin.js



define([
'jquery',
'mage/utils/wrapper',
'Magento_Checkout/js/model/quote'
], function ($, wrapper,quote)
'use strict';

return function (setShippingInformationAction)
return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

if (messageContainer.custom_attributes != undefined)
$.each(messageContainer.custom_attributes , function( key, value )
messageContainer['custom_attributes'][key] = 'attribute_code':key,'value':value;
);


return originalAction(messageContainer);
);
;
);


Step8 : Create file: view/frontend/web/js/action/set-billing-address-mixin.js



define([
'jquery',
'mage/utils/wrapper',
'Magento_Checkout/js/model/quote'
], function ($, wrapper,quote)
'use strict';

return function (setBillingAddressAction)
return wrapper.wrap(setBillingAddressAction, function (originalAction, messageContainer)

var billingAddress = quote.billingAddress();

if(billingAddress != undefined)

if (billingAddress['extension_attributes'] === undefined)
billingAddress['extension_attributes'] = ;


if (billingAddress.customAttributes != undefined)
$.each(billingAddress.customAttributes, function (key, value)

if($.isPlainObject(value))
value = value['value'];


billingAddress['extension_attributes'][key] = value;
);




return originalAction(messageContainer);
);
;
);


Step9 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/set-shipping-information-mixin.js



define([
'jquery',
'mage/utils/wrapper',
'Magento_Checkout/js/model/quote'
], function ($, wrapper,quote)
'use strict';

return function (setShippingInformationAction)
return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

var shippingAddress = quote.shippingAddress();

if (shippingAddress['extension_attributes'] === undefined)
shippingAddress['extension_attributes'] = ;


if (shippingAddress.customAttributes != undefined)
$.each(shippingAddress.customAttributes , function( key, value )

if($.isPlainObject(value))
value = value['value'];


shippingAddress['customAttributes'][key] = value;
shippingAddress['extension_attributes'][key] = value;

);


return originalAction(messageContainer);
);
;
);


Step10 : Create file: Adamsmage/Checkoutattribute/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="MagentoQuoteModelBillingAddressManagement">
<plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_BillingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelBillingAddressManagement"/>
</type>
<type name="MagentoQuoteModelShippingAddressManagement">
<plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_ShippingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelShippingAddressManagement"/>
</type>
</config>


Step11 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/BillingAddressManagement.php



<?php


namespace AdamsmageCheckoutattributePluginMagentoQuoteModel;

class BillingAddressManagement


protected $logger;

public function __construct(
PsrLogLoggerInterface $logger
)
$this->logger = $logger;


public function beforeAssign(
MagentoQuoteModelBillingAddressManagement $subject,
$cartId,
MagentoQuoteApiDataAddressInterface $address,
$useForShipping = false
)

$extAttributes = $address->getExtensionAttributes();
if (!empty($extAttributes))

try
$address->setExample($extAttributes->getExample());
catch (Exception $e)
$this->logger->critical($e->getMessage());








Step12 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/ShippingAddressManagement.php



<?php


namespace AdamsmageAdamsmage_CheckoutattributePluginMagentoQuoteModel;

class ShippingAddressManagement


protected $logger;

public function __construct(
PsrLogLoggerInterface $logger
)
$this->logger = $logger;


public function beforeAssign(
MagentoQuoteModelShippingAddressManagement $subject,
$cartId,
MagentoQuoteApiDataAddressInterface $address
)

$extAttributes = $address->getExtensionAttributes();
if (!empty($extAttributes))

try
$address->setExample($extAttributes->getExample());
catch (Exception $e)
$this->logger->critical($e->getMessage());











share|improve this answer

























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f194705%2fmagento-2-add-extra-text-field-in-checkout-billing-address-and-save-it-in-orde%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Step 1: Create File: Adamsmage/Checkoutattribute/Setup/InstallData.php



    <?php
    namespace AdamsmageCheckoutattributeSetup;

    use MagentoFrameworkSetupInstallDataInterface;
    use MagentoFrameworkSetupModuleContextInterface;
    use MagentoFrameworkSetupModuleDataSetupInterface;
    use MagentoCustomerModelCustomer;
    use MagentoCustomerSetupCustomerSetupFactory;

    class InstallData implements InstallDataInterface


    private $customerSetupFactory;

    /**
    * Constructor
    *
    * @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
    */
    public function __construct(
    CustomerSetupFactory $customerSetupFactory
    )
    $this->customerSetupFactory = $customerSetupFactory;


    /**
    * @inheritdoc
    */
    public function install(
    ModuleDataSetupInterface $setup,
    ModuleContextInterface $context
    )
    $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

    $customerSetup->addAttribute('customer_address', 'example', [
    'label' => 'example',
    'input' => 'text',
    'type' => 'varchar',
    'source' => '',
    'required' => false,
    'position' => 333,
    'visible' => true,
    'system' => false,
    'is_used_in_grid' => false,
    'is_visible_in_grid' => false,
    'is_filterable_in_grid' => false,
    'is_searchable_in_grid' => false,
    'backend' => ''
    ]);


    $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'example')
    ->addData(['used_in_forms' => [
    'customer_address_edit',
    'customer_register_address'
    ]]);
    $attribute->save();

    $installer->getConnection()->addColumn(
    $installer->getTable('quote_address'),
    'example',
    [
    'type' => 'varchar',
    'length' => 255
    ]
    );

    $installer->getConnection()->addColumn(
    $installer->getTable('sales_order_address'),
    'example',
    [
    'type' => 'varchar',
    'length' => 255
    ]
    );




    Step 2: Create File: Adamsmage/Checkoutattribute/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="MagentoCustomerApiDataAddressInterface">
    <attribute code="example" type="string"/>
    </extension_attributes>
    </config>


    Step 3: Create File: Adamsmage/Checkoutattribute/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="MagentoCheckoutBlockOnepage">
    <arguments>
    <argument name="layoutProcessors" xsi:type="array">
    <item name="adamsmage_extra_checkout_address_fields_layoutprocessor" xsi:type="object">AdamsmageCheckoutattributeBlockCheckoutLayoutProcessor</item>
    </argument>
    </arguments>
    </type>
    </config>


    Step4 : Create File: Adamsmage/Checkoutattribute/Block/Checkout/LayoutProcessor.php



    <?php

    namespace AdamsmageCheckoutattributeBlockCheckout;

    class LayoutProcessor implements MagentoCheckoutBlockCheckoutLayoutProcessorInterface
    {

    public function process($result)
    $result = $this->getShippingFormFields($result);
    $result = $this->getBillingFormFields($result);
    return $result;


    public function getAdditionalFields($addressType='shipping')
    if($addressType=='shipping')
    return ['example'];

    return ['example'];


    public function getShippingFormFields($result)
    if(isset($result['components']['checkout']['children']['steps']['children']
    ['shipping-step']['children']['shippingAddress']['children']
    ['shipping-address-fieldset'])
    )

    $shippingPostcodeFields = $this->getFields('shippingAddress.custom_attributes','shipping');

    $shippingFields = $result['components']['checkout']['children']['steps']['children']
    ['shipping-step']['children']['shippingAddress']['children']
    ['shipping-address-fieldset']['children'];

    if(isset($shippingFields['street']))
    unset($shippingFields['street']['children'][1]['validation']);
    unset($shippingFields['street']['children'][2]['validation']);


    $shippingFields = array_replace_recursive($shippingFields,$shippingPostcodeFields);

    $result['components']['checkout']['children']['steps']['children']
    ['shipping-step']['children']['shippingAddress']['children']
    ['shipping-address-fieldset']['children'] = $shippingFields;



    return $result;


    public function getBillingFormFields($result)
    if(isset($result['components']['checkout']['children']['steps']['children']
    ['billing-step']['children']['payment']['children']
    ['payments-list']))

    $paymentForms = $result['components']['checkout']['children']['steps']['children']
    ['billing-step']['children']['payment']['children']
    ['payments-list']['children'];

    foreach ($paymentForms as $paymentMethodForm => $paymentMethodValue)

    $paymentMethodCode = str_replace('-form', '', $paymentMethodForm);

    if (!isset($result['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children'][$paymentMethodCode . '-form']))
    continue;


    $billingFields = $result['components']['checkout']['children']['steps']['children']
    ['billing-step']['children']['payment']['children']
    ['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'];

    $billingPostcodeFields = $this->getFields('billingAddress' . $paymentMethodCode . '.custom_attributes','billing');

    $billingFields = array_replace_recursive($billingFields, $billingPostcodeFields);

    $result['components']['checkout']['children']['steps']['children']
    ['billing-step']['children']['payment']['children']
    ['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'] = $billingFields;



    return $result;


    public function getFields($scope,$addressType)
    $fields = [];
    foreach($this->getAdditionalFields($addressType) as $field)
    $fields[$field] = $this->getField($field,$scope);

    return $fields;


    public function getField($attributeCode,$scope)
    $field = [
    'config' => [
    'customScope' => $scope,
    ],
    'dataScope' => $scope . '.'.$attributeCode,
    ];

    return $field;



    Step5 : Modify file: Adamsmage/Checkoutattribute/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="Adamsmage_Checkoutattribute" setup_version="1.0.0">
    <sequence>
    <module name="Magento_Checkout"/>
    </sequence>
    </module>
    </config>


    Step6 : Create file: Adamsmage/Checkoutattribute/view/frontend/requirejs-config.js



    var config = 
    config:
    mixins:
    'Magento_Checkout/js/action/set-billing-address':
    'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
    ,
    'Magento_Checkout/js/action/set-shipping-information':
    'Adamsmage_Checkoutattribute/js/action/set-shipping-information-mixin': true
    ,
    'Magento_Checkout/js/action/create-shipping-address':
    'Adamsmage_Checkoutattribute/js/action/create-shipping-address-mixin': true
    ,
    'Magento_Checkout/js/action/place-order':
    'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
    ,
    'Magento_Checkout/js/action/create-billing-address':
    'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true



    ;


    Step7 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/create-shipping-address-mixin.js



    define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote'
    ], function ($, wrapper,quote)
    'use strict';

    return function (setShippingInformationAction)
    return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

    if (messageContainer.custom_attributes != undefined)
    $.each(messageContainer.custom_attributes , function( key, value )
    messageContainer['custom_attributes'][key] = 'attribute_code':key,'value':value;
    );


    return originalAction(messageContainer);
    );
    ;
    );


    Step8 : Create file: view/frontend/web/js/action/set-billing-address-mixin.js



    define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote'
    ], function ($, wrapper,quote)
    'use strict';

    return function (setBillingAddressAction)
    return wrapper.wrap(setBillingAddressAction, function (originalAction, messageContainer)

    var billingAddress = quote.billingAddress();

    if(billingAddress != undefined)

    if (billingAddress['extension_attributes'] === undefined)
    billingAddress['extension_attributes'] = ;


    if (billingAddress.customAttributes != undefined)
    $.each(billingAddress.customAttributes, function (key, value)

    if($.isPlainObject(value))
    value = value['value'];


    billingAddress['extension_attributes'][key] = value;
    );




    return originalAction(messageContainer);
    );
    ;
    );


    Step9 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/set-shipping-information-mixin.js



    define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote'
    ], function ($, wrapper,quote)
    'use strict';

    return function (setShippingInformationAction)
    return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

    var shippingAddress = quote.shippingAddress();

    if (shippingAddress['extension_attributes'] === undefined)
    shippingAddress['extension_attributes'] = ;


    if (shippingAddress.customAttributes != undefined)
    $.each(shippingAddress.customAttributes , function( key, value )

    if($.isPlainObject(value))
    value = value['value'];


    shippingAddress['customAttributes'][key] = value;
    shippingAddress['extension_attributes'][key] = value;

    );


    return originalAction(messageContainer);
    );
    ;
    );


    Step10 : Create file: Adamsmage/Checkoutattribute/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="MagentoQuoteModelBillingAddressManagement">
    <plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_BillingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelBillingAddressManagement"/>
    </type>
    <type name="MagentoQuoteModelShippingAddressManagement">
    <plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_ShippingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelShippingAddressManagement"/>
    </type>
    </config>


    Step11 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/BillingAddressManagement.php



    <?php


    namespace AdamsmageCheckoutattributePluginMagentoQuoteModel;

    class BillingAddressManagement


    protected $logger;

    public function __construct(
    PsrLogLoggerInterface $logger
    )
    $this->logger = $logger;


    public function beforeAssign(
    MagentoQuoteModelBillingAddressManagement $subject,
    $cartId,
    MagentoQuoteApiDataAddressInterface $address,
    $useForShipping = false
    )

    $extAttributes = $address->getExtensionAttributes();
    if (!empty($extAttributes))

    try
    $address->setExample($extAttributes->getExample());
    catch (Exception $e)
    $this->logger->critical($e->getMessage());








    Step12 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/ShippingAddressManagement.php



    <?php


    namespace AdamsmageAdamsmage_CheckoutattributePluginMagentoQuoteModel;

    class ShippingAddressManagement


    protected $logger;

    public function __construct(
    PsrLogLoggerInterface $logger
    )
    $this->logger = $logger;


    public function beforeAssign(
    MagentoQuoteModelShippingAddressManagement $subject,
    $cartId,
    MagentoQuoteApiDataAddressInterface $address
    )

    $extAttributes = $address->getExtensionAttributes();
    if (!empty($extAttributes))

    try
    $address->setExample($extAttributes->getExample());
    catch (Exception $e)
    $this->logger->critical($e->getMessage());











    share|improve this answer



























      0














      Step 1: Create File: Adamsmage/Checkoutattribute/Setup/InstallData.php



      <?php
      namespace AdamsmageCheckoutattributeSetup;

      use MagentoFrameworkSetupInstallDataInterface;
      use MagentoFrameworkSetupModuleContextInterface;
      use MagentoFrameworkSetupModuleDataSetupInterface;
      use MagentoCustomerModelCustomer;
      use MagentoCustomerSetupCustomerSetupFactory;

      class InstallData implements InstallDataInterface


      private $customerSetupFactory;

      /**
      * Constructor
      *
      * @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
      */
      public function __construct(
      CustomerSetupFactory $customerSetupFactory
      )
      $this->customerSetupFactory = $customerSetupFactory;


      /**
      * @inheritdoc
      */
      public function install(
      ModuleDataSetupInterface $setup,
      ModuleContextInterface $context
      )
      $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

      $customerSetup->addAttribute('customer_address', 'example', [
      'label' => 'example',
      'input' => 'text',
      'type' => 'varchar',
      'source' => '',
      'required' => false,
      'position' => 333,
      'visible' => true,
      'system' => false,
      'is_used_in_grid' => false,
      'is_visible_in_grid' => false,
      'is_filterable_in_grid' => false,
      'is_searchable_in_grid' => false,
      'backend' => ''
      ]);


      $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'example')
      ->addData(['used_in_forms' => [
      'customer_address_edit',
      'customer_register_address'
      ]]);
      $attribute->save();

      $installer->getConnection()->addColumn(
      $installer->getTable('quote_address'),
      'example',
      [
      'type' => 'varchar',
      'length' => 255
      ]
      );

      $installer->getConnection()->addColumn(
      $installer->getTable('sales_order_address'),
      'example',
      [
      'type' => 'varchar',
      'length' => 255
      ]
      );




      Step 2: Create File: Adamsmage/Checkoutattribute/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="MagentoCustomerApiDataAddressInterface">
      <attribute code="example" type="string"/>
      </extension_attributes>
      </config>


      Step 3: Create File: Adamsmage/Checkoutattribute/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="MagentoCheckoutBlockOnepage">
      <arguments>
      <argument name="layoutProcessors" xsi:type="array">
      <item name="adamsmage_extra_checkout_address_fields_layoutprocessor" xsi:type="object">AdamsmageCheckoutattributeBlockCheckoutLayoutProcessor</item>
      </argument>
      </arguments>
      </type>
      </config>


      Step4 : Create File: Adamsmage/Checkoutattribute/Block/Checkout/LayoutProcessor.php



      <?php

      namespace AdamsmageCheckoutattributeBlockCheckout;

      class LayoutProcessor implements MagentoCheckoutBlockCheckoutLayoutProcessorInterface
      {

      public function process($result)
      $result = $this->getShippingFormFields($result);
      $result = $this->getBillingFormFields($result);
      return $result;


      public function getAdditionalFields($addressType='shipping')
      if($addressType=='shipping')
      return ['example'];

      return ['example'];


      public function getShippingFormFields($result)
      if(isset($result['components']['checkout']['children']['steps']['children']
      ['shipping-step']['children']['shippingAddress']['children']
      ['shipping-address-fieldset'])
      )

      $shippingPostcodeFields = $this->getFields('shippingAddress.custom_attributes','shipping');

      $shippingFields = $result['components']['checkout']['children']['steps']['children']
      ['shipping-step']['children']['shippingAddress']['children']
      ['shipping-address-fieldset']['children'];

      if(isset($shippingFields['street']))
      unset($shippingFields['street']['children'][1]['validation']);
      unset($shippingFields['street']['children'][2]['validation']);


      $shippingFields = array_replace_recursive($shippingFields,$shippingPostcodeFields);

      $result['components']['checkout']['children']['steps']['children']
      ['shipping-step']['children']['shippingAddress']['children']
      ['shipping-address-fieldset']['children'] = $shippingFields;



      return $result;


      public function getBillingFormFields($result)
      if(isset($result['components']['checkout']['children']['steps']['children']
      ['billing-step']['children']['payment']['children']
      ['payments-list']))

      $paymentForms = $result['components']['checkout']['children']['steps']['children']
      ['billing-step']['children']['payment']['children']
      ['payments-list']['children'];

      foreach ($paymentForms as $paymentMethodForm => $paymentMethodValue)

      $paymentMethodCode = str_replace('-form', '', $paymentMethodForm);

      if (!isset($result['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children'][$paymentMethodCode . '-form']))
      continue;


      $billingFields = $result['components']['checkout']['children']['steps']['children']
      ['billing-step']['children']['payment']['children']
      ['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'];

      $billingPostcodeFields = $this->getFields('billingAddress' . $paymentMethodCode . '.custom_attributes','billing');

      $billingFields = array_replace_recursive($billingFields, $billingPostcodeFields);

      $result['components']['checkout']['children']['steps']['children']
      ['billing-step']['children']['payment']['children']
      ['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'] = $billingFields;



      return $result;


      public function getFields($scope,$addressType)
      $fields = [];
      foreach($this->getAdditionalFields($addressType) as $field)
      $fields[$field] = $this->getField($field,$scope);

      return $fields;


      public function getField($attributeCode,$scope)
      $field = [
      'config' => [
      'customScope' => $scope,
      ],
      'dataScope' => $scope . '.'.$attributeCode,
      ];

      return $field;



      Step5 : Modify file: Adamsmage/Checkoutattribute/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="Adamsmage_Checkoutattribute" setup_version="1.0.0">
      <sequence>
      <module name="Magento_Checkout"/>
      </sequence>
      </module>
      </config>


      Step6 : Create file: Adamsmage/Checkoutattribute/view/frontend/requirejs-config.js



      var config = 
      config:
      mixins:
      'Magento_Checkout/js/action/set-billing-address':
      'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
      ,
      'Magento_Checkout/js/action/set-shipping-information':
      'Adamsmage_Checkoutattribute/js/action/set-shipping-information-mixin': true
      ,
      'Magento_Checkout/js/action/create-shipping-address':
      'Adamsmage_Checkoutattribute/js/action/create-shipping-address-mixin': true
      ,
      'Magento_Checkout/js/action/place-order':
      'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
      ,
      'Magento_Checkout/js/action/create-billing-address':
      'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true



      ;


      Step7 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/create-shipping-address-mixin.js



      define([
      'jquery',
      'mage/utils/wrapper',
      'Magento_Checkout/js/model/quote'
      ], function ($, wrapper,quote)
      'use strict';

      return function (setShippingInformationAction)
      return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

      if (messageContainer.custom_attributes != undefined)
      $.each(messageContainer.custom_attributes , function( key, value )
      messageContainer['custom_attributes'][key] = 'attribute_code':key,'value':value;
      );


      return originalAction(messageContainer);
      );
      ;
      );


      Step8 : Create file: view/frontend/web/js/action/set-billing-address-mixin.js



      define([
      'jquery',
      'mage/utils/wrapper',
      'Magento_Checkout/js/model/quote'
      ], function ($, wrapper,quote)
      'use strict';

      return function (setBillingAddressAction)
      return wrapper.wrap(setBillingAddressAction, function (originalAction, messageContainer)

      var billingAddress = quote.billingAddress();

      if(billingAddress != undefined)

      if (billingAddress['extension_attributes'] === undefined)
      billingAddress['extension_attributes'] = ;


      if (billingAddress.customAttributes != undefined)
      $.each(billingAddress.customAttributes, function (key, value)

      if($.isPlainObject(value))
      value = value['value'];


      billingAddress['extension_attributes'][key] = value;
      );




      return originalAction(messageContainer);
      );
      ;
      );


      Step9 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/set-shipping-information-mixin.js



      define([
      'jquery',
      'mage/utils/wrapper',
      'Magento_Checkout/js/model/quote'
      ], function ($, wrapper,quote)
      'use strict';

      return function (setShippingInformationAction)
      return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

      var shippingAddress = quote.shippingAddress();

      if (shippingAddress['extension_attributes'] === undefined)
      shippingAddress['extension_attributes'] = ;


      if (shippingAddress.customAttributes != undefined)
      $.each(shippingAddress.customAttributes , function( key, value )

      if($.isPlainObject(value))
      value = value['value'];


      shippingAddress['customAttributes'][key] = value;
      shippingAddress['extension_attributes'][key] = value;

      );


      return originalAction(messageContainer);
      );
      ;
      );


      Step10 : Create file: Adamsmage/Checkoutattribute/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="MagentoQuoteModelBillingAddressManagement">
      <plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_BillingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelBillingAddressManagement"/>
      </type>
      <type name="MagentoQuoteModelShippingAddressManagement">
      <plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_ShippingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelShippingAddressManagement"/>
      </type>
      </config>


      Step11 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/BillingAddressManagement.php



      <?php


      namespace AdamsmageCheckoutattributePluginMagentoQuoteModel;

      class BillingAddressManagement


      protected $logger;

      public function __construct(
      PsrLogLoggerInterface $logger
      )
      $this->logger = $logger;


      public function beforeAssign(
      MagentoQuoteModelBillingAddressManagement $subject,
      $cartId,
      MagentoQuoteApiDataAddressInterface $address,
      $useForShipping = false
      )

      $extAttributes = $address->getExtensionAttributes();
      if (!empty($extAttributes))

      try
      $address->setExample($extAttributes->getExample());
      catch (Exception $e)
      $this->logger->critical($e->getMessage());








      Step12 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/ShippingAddressManagement.php



      <?php


      namespace AdamsmageAdamsmage_CheckoutattributePluginMagentoQuoteModel;

      class ShippingAddressManagement


      protected $logger;

      public function __construct(
      PsrLogLoggerInterface $logger
      )
      $this->logger = $logger;


      public function beforeAssign(
      MagentoQuoteModelShippingAddressManagement $subject,
      $cartId,
      MagentoQuoteApiDataAddressInterface $address
      )

      $extAttributes = $address->getExtensionAttributes();
      if (!empty($extAttributes))

      try
      $address->setExample($extAttributes->getExample());
      catch (Exception $e)
      $this->logger->critical($e->getMessage());











      share|improve this answer

























        0












        0








        0







        Step 1: Create File: Adamsmage/Checkoutattribute/Setup/InstallData.php



        <?php
        namespace AdamsmageCheckoutattributeSetup;

        use MagentoFrameworkSetupInstallDataInterface;
        use MagentoFrameworkSetupModuleContextInterface;
        use MagentoFrameworkSetupModuleDataSetupInterface;
        use MagentoCustomerModelCustomer;
        use MagentoCustomerSetupCustomerSetupFactory;

        class InstallData implements InstallDataInterface


        private $customerSetupFactory;

        /**
        * Constructor
        *
        * @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
        */
        public function __construct(
        CustomerSetupFactory $customerSetupFactory
        )
        $this->customerSetupFactory = $customerSetupFactory;


        /**
        * @inheritdoc
        */
        public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
        )
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerSetup->addAttribute('customer_address', 'example', [
        'label' => 'example',
        'input' => 'text',
        'type' => 'varchar',
        'source' => '',
        'required' => false,
        'position' => 333,
        'visible' => true,
        'system' => false,
        'is_used_in_grid' => false,
        'is_visible_in_grid' => false,
        'is_filterable_in_grid' => false,
        'is_searchable_in_grid' => false,
        'backend' => ''
        ]);


        $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'example')
        ->addData(['used_in_forms' => [
        'customer_address_edit',
        'customer_register_address'
        ]]);
        $attribute->save();

        $installer->getConnection()->addColumn(
        $installer->getTable('quote_address'),
        'example',
        [
        'type' => 'varchar',
        'length' => 255
        ]
        );

        $installer->getConnection()->addColumn(
        $installer->getTable('sales_order_address'),
        'example',
        [
        'type' => 'varchar',
        'length' => 255
        ]
        );




        Step 2: Create File: Adamsmage/Checkoutattribute/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="MagentoCustomerApiDataAddressInterface">
        <attribute code="example" type="string"/>
        </extension_attributes>
        </config>


        Step 3: Create File: Adamsmage/Checkoutattribute/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="MagentoCheckoutBlockOnepage">
        <arguments>
        <argument name="layoutProcessors" xsi:type="array">
        <item name="adamsmage_extra_checkout_address_fields_layoutprocessor" xsi:type="object">AdamsmageCheckoutattributeBlockCheckoutLayoutProcessor</item>
        </argument>
        </arguments>
        </type>
        </config>


        Step4 : Create File: Adamsmage/Checkoutattribute/Block/Checkout/LayoutProcessor.php



        <?php

        namespace AdamsmageCheckoutattributeBlockCheckout;

        class LayoutProcessor implements MagentoCheckoutBlockCheckoutLayoutProcessorInterface
        {

        public function process($result)
        $result = $this->getShippingFormFields($result);
        $result = $this->getBillingFormFields($result);
        return $result;


        public function getAdditionalFields($addressType='shipping')
        if($addressType=='shipping')
        return ['example'];

        return ['example'];


        public function getShippingFormFields($result)
        if(isset($result['components']['checkout']['children']['steps']['children']
        ['shipping-step']['children']['shippingAddress']['children']
        ['shipping-address-fieldset'])
        )

        $shippingPostcodeFields = $this->getFields('shippingAddress.custom_attributes','shipping');

        $shippingFields = $result['components']['checkout']['children']['steps']['children']
        ['shipping-step']['children']['shippingAddress']['children']
        ['shipping-address-fieldset']['children'];

        if(isset($shippingFields['street']))
        unset($shippingFields['street']['children'][1]['validation']);
        unset($shippingFields['street']['children'][2]['validation']);


        $shippingFields = array_replace_recursive($shippingFields,$shippingPostcodeFields);

        $result['components']['checkout']['children']['steps']['children']
        ['shipping-step']['children']['shippingAddress']['children']
        ['shipping-address-fieldset']['children'] = $shippingFields;



        return $result;


        public function getBillingFormFields($result)
        if(isset($result['components']['checkout']['children']['steps']['children']
        ['billing-step']['children']['payment']['children']
        ['payments-list']))

        $paymentForms = $result['components']['checkout']['children']['steps']['children']
        ['billing-step']['children']['payment']['children']
        ['payments-list']['children'];

        foreach ($paymentForms as $paymentMethodForm => $paymentMethodValue)

        $paymentMethodCode = str_replace('-form', '', $paymentMethodForm);

        if (!isset($result['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children'][$paymentMethodCode . '-form']))
        continue;


        $billingFields = $result['components']['checkout']['children']['steps']['children']
        ['billing-step']['children']['payment']['children']
        ['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'];

        $billingPostcodeFields = $this->getFields('billingAddress' . $paymentMethodCode . '.custom_attributes','billing');

        $billingFields = array_replace_recursive($billingFields, $billingPostcodeFields);

        $result['components']['checkout']['children']['steps']['children']
        ['billing-step']['children']['payment']['children']
        ['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'] = $billingFields;



        return $result;


        public function getFields($scope,$addressType)
        $fields = [];
        foreach($this->getAdditionalFields($addressType) as $field)
        $fields[$field] = $this->getField($field,$scope);

        return $fields;


        public function getField($attributeCode,$scope)
        $field = [
        'config' => [
        'customScope' => $scope,
        ],
        'dataScope' => $scope . '.'.$attributeCode,
        ];

        return $field;



        Step5 : Modify file: Adamsmage/Checkoutattribute/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="Adamsmage_Checkoutattribute" setup_version="1.0.0">
        <sequence>
        <module name="Magento_Checkout"/>
        </sequence>
        </module>
        </config>


        Step6 : Create file: Adamsmage/Checkoutattribute/view/frontend/requirejs-config.js



        var config = 
        config:
        mixins:
        'Magento_Checkout/js/action/set-billing-address':
        'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
        ,
        'Magento_Checkout/js/action/set-shipping-information':
        'Adamsmage_Checkoutattribute/js/action/set-shipping-information-mixin': true
        ,
        'Magento_Checkout/js/action/create-shipping-address':
        'Adamsmage_Checkoutattribute/js/action/create-shipping-address-mixin': true
        ,
        'Magento_Checkout/js/action/place-order':
        'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
        ,
        'Magento_Checkout/js/action/create-billing-address':
        'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true



        ;


        Step7 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/create-shipping-address-mixin.js



        define([
        'jquery',
        'mage/utils/wrapper',
        'Magento_Checkout/js/model/quote'
        ], function ($, wrapper,quote)
        'use strict';

        return function (setShippingInformationAction)
        return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

        if (messageContainer.custom_attributes != undefined)
        $.each(messageContainer.custom_attributes , function( key, value )
        messageContainer['custom_attributes'][key] = 'attribute_code':key,'value':value;
        );


        return originalAction(messageContainer);
        );
        ;
        );


        Step8 : Create file: view/frontend/web/js/action/set-billing-address-mixin.js



        define([
        'jquery',
        'mage/utils/wrapper',
        'Magento_Checkout/js/model/quote'
        ], function ($, wrapper,quote)
        'use strict';

        return function (setBillingAddressAction)
        return wrapper.wrap(setBillingAddressAction, function (originalAction, messageContainer)

        var billingAddress = quote.billingAddress();

        if(billingAddress != undefined)

        if (billingAddress['extension_attributes'] === undefined)
        billingAddress['extension_attributes'] = ;


        if (billingAddress.customAttributes != undefined)
        $.each(billingAddress.customAttributes, function (key, value)

        if($.isPlainObject(value))
        value = value['value'];


        billingAddress['extension_attributes'][key] = value;
        );




        return originalAction(messageContainer);
        );
        ;
        );


        Step9 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/set-shipping-information-mixin.js



        define([
        'jquery',
        'mage/utils/wrapper',
        'Magento_Checkout/js/model/quote'
        ], function ($, wrapper,quote)
        'use strict';

        return function (setShippingInformationAction)
        return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

        var shippingAddress = quote.shippingAddress();

        if (shippingAddress['extension_attributes'] === undefined)
        shippingAddress['extension_attributes'] = ;


        if (shippingAddress.customAttributes != undefined)
        $.each(shippingAddress.customAttributes , function( key, value )

        if($.isPlainObject(value))
        value = value['value'];


        shippingAddress['customAttributes'][key] = value;
        shippingAddress['extension_attributes'][key] = value;

        );


        return originalAction(messageContainer);
        );
        ;
        );


        Step10 : Create file: Adamsmage/Checkoutattribute/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="MagentoQuoteModelBillingAddressManagement">
        <plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_BillingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelBillingAddressManagement"/>
        </type>
        <type name="MagentoQuoteModelShippingAddressManagement">
        <plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_ShippingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelShippingAddressManagement"/>
        </type>
        </config>


        Step11 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/BillingAddressManagement.php



        <?php


        namespace AdamsmageCheckoutattributePluginMagentoQuoteModel;

        class BillingAddressManagement


        protected $logger;

        public function __construct(
        PsrLogLoggerInterface $logger
        )
        $this->logger = $logger;


        public function beforeAssign(
        MagentoQuoteModelBillingAddressManagement $subject,
        $cartId,
        MagentoQuoteApiDataAddressInterface $address,
        $useForShipping = false
        )

        $extAttributes = $address->getExtensionAttributes();
        if (!empty($extAttributes))

        try
        $address->setExample($extAttributes->getExample());
        catch (Exception $e)
        $this->logger->critical($e->getMessage());








        Step12 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/ShippingAddressManagement.php



        <?php


        namespace AdamsmageAdamsmage_CheckoutattributePluginMagentoQuoteModel;

        class ShippingAddressManagement


        protected $logger;

        public function __construct(
        PsrLogLoggerInterface $logger
        )
        $this->logger = $logger;


        public function beforeAssign(
        MagentoQuoteModelShippingAddressManagement $subject,
        $cartId,
        MagentoQuoteApiDataAddressInterface $address
        )

        $extAttributes = $address->getExtensionAttributes();
        if (!empty($extAttributes))

        try
        $address->setExample($extAttributes->getExample());
        catch (Exception $e)
        $this->logger->critical($e->getMessage());











        share|improve this answer













        Step 1: Create File: Adamsmage/Checkoutattribute/Setup/InstallData.php



        <?php
        namespace AdamsmageCheckoutattributeSetup;

        use MagentoFrameworkSetupInstallDataInterface;
        use MagentoFrameworkSetupModuleContextInterface;
        use MagentoFrameworkSetupModuleDataSetupInterface;
        use MagentoCustomerModelCustomer;
        use MagentoCustomerSetupCustomerSetupFactory;

        class InstallData implements InstallDataInterface


        private $customerSetupFactory;

        /**
        * Constructor
        *
        * @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
        */
        public function __construct(
        CustomerSetupFactory $customerSetupFactory
        )
        $this->customerSetupFactory = $customerSetupFactory;


        /**
        * @inheritdoc
        */
        public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
        )
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerSetup->addAttribute('customer_address', 'example', [
        'label' => 'example',
        'input' => 'text',
        'type' => 'varchar',
        'source' => '',
        'required' => false,
        'position' => 333,
        'visible' => true,
        'system' => false,
        'is_used_in_grid' => false,
        'is_visible_in_grid' => false,
        'is_filterable_in_grid' => false,
        'is_searchable_in_grid' => false,
        'backend' => ''
        ]);


        $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'example')
        ->addData(['used_in_forms' => [
        'customer_address_edit',
        'customer_register_address'
        ]]);
        $attribute->save();

        $installer->getConnection()->addColumn(
        $installer->getTable('quote_address'),
        'example',
        [
        'type' => 'varchar',
        'length' => 255
        ]
        );

        $installer->getConnection()->addColumn(
        $installer->getTable('sales_order_address'),
        'example',
        [
        'type' => 'varchar',
        'length' => 255
        ]
        );




        Step 2: Create File: Adamsmage/Checkoutattribute/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="MagentoCustomerApiDataAddressInterface">
        <attribute code="example" type="string"/>
        </extension_attributes>
        </config>


        Step 3: Create File: Adamsmage/Checkoutattribute/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="MagentoCheckoutBlockOnepage">
        <arguments>
        <argument name="layoutProcessors" xsi:type="array">
        <item name="adamsmage_extra_checkout_address_fields_layoutprocessor" xsi:type="object">AdamsmageCheckoutattributeBlockCheckoutLayoutProcessor</item>
        </argument>
        </arguments>
        </type>
        </config>


        Step4 : Create File: Adamsmage/Checkoutattribute/Block/Checkout/LayoutProcessor.php



        <?php

        namespace AdamsmageCheckoutattributeBlockCheckout;

        class LayoutProcessor implements MagentoCheckoutBlockCheckoutLayoutProcessorInterface
        {

        public function process($result)
        $result = $this->getShippingFormFields($result);
        $result = $this->getBillingFormFields($result);
        return $result;


        public function getAdditionalFields($addressType='shipping')
        if($addressType=='shipping')
        return ['example'];

        return ['example'];


        public function getShippingFormFields($result)
        if(isset($result['components']['checkout']['children']['steps']['children']
        ['shipping-step']['children']['shippingAddress']['children']
        ['shipping-address-fieldset'])
        )

        $shippingPostcodeFields = $this->getFields('shippingAddress.custom_attributes','shipping');

        $shippingFields = $result['components']['checkout']['children']['steps']['children']
        ['shipping-step']['children']['shippingAddress']['children']
        ['shipping-address-fieldset']['children'];

        if(isset($shippingFields['street']))
        unset($shippingFields['street']['children'][1]['validation']);
        unset($shippingFields['street']['children'][2]['validation']);


        $shippingFields = array_replace_recursive($shippingFields,$shippingPostcodeFields);

        $result['components']['checkout']['children']['steps']['children']
        ['shipping-step']['children']['shippingAddress']['children']
        ['shipping-address-fieldset']['children'] = $shippingFields;



        return $result;


        public function getBillingFormFields($result)
        if(isset($result['components']['checkout']['children']['steps']['children']
        ['billing-step']['children']['payment']['children']
        ['payments-list']))

        $paymentForms = $result['components']['checkout']['children']['steps']['children']
        ['billing-step']['children']['payment']['children']
        ['payments-list']['children'];

        foreach ($paymentForms as $paymentMethodForm => $paymentMethodValue)

        $paymentMethodCode = str_replace('-form', '', $paymentMethodForm);

        if (!isset($result['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children'][$paymentMethodCode . '-form']))
        continue;


        $billingFields = $result['components']['checkout']['children']['steps']['children']
        ['billing-step']['children']['payment']['children']
        ['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'];

        $billingPostcodeFields = $this->getFields('billingAddress' . $paymentMethodCode . '.custom_attributes','billing');

        $billingFields = array_replace_recursive($billingFields, $billingPostcodeFields);

        $result['components']['checkout']['children']['steps']['children']
        ['billing-step']['children']['payment']['children']
        ['payments-list']['children'][$paymentMethodCode . '-form']['children']['form-fields']['children'] = $billingFields;



        return $result;


        public function getFields($scope,$addressType)
        $fields = [];
        foreach($this->getAdditionalFields($addressType) as $field)
        $fields[$field] = $this->getField($field,$scope);

        return $fields;


        public function getField($attributeCode,$scope)
        $field = [
        'config' => [
        'customScope' => $scope,
        ],
        'dataScope' => $scope . '.'.$attributeCode,
        ];

        return $field;



        Step5 : Modify file: Adamsmage/Checkoutattribute/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="Adamsmage_Checkoutattribute" setup_version="1.0.0">
        <sequence>
        <module name="Magento_Checkout"/>
        </sequence>
        </module>
        </config>


        Step6 : Create file: Adamsmage/Checkoutattribute/view/frontend/requirejs-config.js



        var config = 
        config:
        mixins:
        'Magento_Checkout/js/action/set-billing-address':
        'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
        ,
        'Magento_Checkout/js/action/set-shipping-information':
        'Adamsmage_Checkoutattribute/js/action/set-shipping-information-mixin': true
        ,
        'Magento_Checkout/js/action/create-shipping-address':
        'Adamsmage_Checkoutattribute/js/action/create-shipping-address-mixin': true
        ,
        'Magento_Checkout/js/action/place-order':
        'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true
        ,
        'Magento_Checkout/js/action/create-billing-address':
        'Adamsmage_Checkoutattribute/js/action/set-billing-address-mixin': true



        ;


        Step7 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/create-shipping-address-mixin.js



        define([
        'jquery',
        'mage/utils/wrapper',
        'Magento_Checkout/js/model/quote'
        ], function ($, wrapper,quote)
        'use strict';

        return function (setShippingInformationAction)
        return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

        if (messageContainer.custom_attributes != undefined)
        $.each(messageContainer.custom_attributes , function( key, value )
        messageContainer['custom_attributes'][key] = 'attribute_code':key,'value':value;
        );


        return originalAction(messageContainer);
        );
        ;
        );


        Step8 : Create file: view/frontend/web/js/action/set-billing-address-mixin.js



        define([
        'jquery',
        'mage/utils/wrapper',
        'Magento_Checkout/js/model/quote'
        ], function ($, wrapper,quote)
        'use strict';

        return function (setBillingAddressAction)
        return wrapper.wrap(setBillingAddressAction, function (originalAction, messageContainer)

        var billingAddress = quote.billingAddress();

        if(billingAddress != undefined)

        if (billingAddress['extension_attributes'] === undefined)
        billingAddress['extension_attributes'] = ;


        if (billingAddress.customAttributes != undefined)
        $.each(billingAddress.customAttributes, function (key, value)

        if($.isPlainObject(value))
        value = value['value'];


        billingAddress['extension_attributes'][key] = value;
        );




        return originalAction(messageContainer);
        );
        ;
        );


        Step9 : Create file: Adamsmage/Checkoutattribute/view/frontend/web/js/action/set-shipping-information-mixin.js



        define([
        'jquery',
        'mage/utils/wrapper',
        'Magento_Checkout/js/model/quote'
        ], function ($, wrapper,quote)
        'use strict';

        return function (setShippingInformationAction)
        return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer)

        var shippingAddress = quote.shippingAddress();

        if (shippingAddress['extension_attributes'] === undefined)
        shippingAddress['extension_attributes'] = ;


        if (shippingAddress.customAttributes != undefined)
        $.each(shippingAddress.customAttributes , function( key, value )

        if($.isPlainObject(value))
        value = value['value'];


        shippingAddress['customAttributes'][key] = value;
        shippingAddress['extension_attributes'][key] = value;

        );


        return originalAction(messageContainer);
        );
        ;
        );


        Step10 : Create file: Adamsmage/Checkoutattribute/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="MagentoQuoteModelBillingAddressManagement">
        <plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_BillingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelBillingAddressManagement"/>
        </type>
        <type name="MagentoQuoteModelShippingAddressManagement">
        <plugin disabled="false" name="Adamsmage_Checkoutattribute_Plugin_Magento_Quote_Model_ShippingAddressManagement" sortOrder="10" type="Adamsmage_CheckoutattributePluginMagentoQuoteModelShippingAddressManagement"/>
        </type>
        </config>


        Step11 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/BillingAddressManagement.php



        <?php


        namespace AdamsmageCheckoutattributePluginMagentoQuoteModel;

        class BillingAddressManagement


        protected $logger;

        public function __construct(
        PsrLogLoggerInterface $logger
        )
        $this->logger = $logger;


        public function beforeAssign(
        MagentoQuoteModelBillingAddressManagement $subject,
        $cartId,
        MagentoQuoteApiDataAddressInterface $address,
        $useForShipping = false
        )

        $extAttributes = $address->getExtensionAttributes();
        if (!empty($extAttributes))

        try
        $address->setExample($extAttributes->getExample());
        catch (Exception $e)
        $this->logger->critical($e->getMessage());








        Step12 : Create file: Adamsmage/Checkoutattribute/Plugin/Magento/Quote/Model/ShippingAddressManagement.php



        <?php


        namespace AdamsmageAdamsmage_CheckoutattributePluginMagentoQuoteModel;

        class ShippingAddressManagement


        protected $logger;

        public function __construct(
        PsrLogLoggerInterface $logger
        )
        $this->logger = $logger;


        public function beforeAssign(
        MagentoQuoteModelShippingAddressManagement $subject,
        $cartId,
        MagentoQuoteApiDataAddressInterface $address
        )

        $extAttributes = $address->getExtensionAttributes();
        if (!empty($extAttributes))

        try
        $address->setExample($extAttributes->getExample());
        catch (Exception $e)
        $this->logger->critical($e->getMessage());












        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jul 5 at 10:24









        Anas MansuriAnas Mansuri

        9221 silver badge16 bronze badges




        9221 silver badge16 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f194705%2fmagento-2-add-extra-text-field-in-checkout-billing-address-and-save-it-in-orde%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Grendel Contents Story Scholarship Depictions Notes References Navigation menu10.1093/notesj/gjn112Berserkeree

            Area configuration aggregation error after install Porto themeMagento 2.1 CE Installed but front/backend not loading/workingCSS not loading on page within Magento 2 pageCannot install module in Magento 2no commands defined in the “setup” namespace. in Magento2Magento 2: Static files are present but shows 404Why do i have to always run the commands to clean cache in Magento 2.1.8?Failure reason: 'Unable to unserialize value.'Error 500 after magento migrationIn production mode the site does not loadMagento 2 : Error 500 after installing

            Middle Expansion Olielle Resaix Definition: Uttering songs of triumph shouting with joy triumphant exulting Sejunction Journal 붙다 달 고급 품목 외출 The stretch trades the screeching tin. Definition: The act of speaking with a drawl a drawl Cough Sand Definition: An uproar a quarrel a noisy outbreak Shake Iron Publicize Horse House Baby 사과 Resaix Flaggy Jelly Temporary Unequaled Puppet A drop in the bucket Shrew 성격 회원 성질 미팅 The burn frames the tacky quality. Materialistic The smoke reduces the way. Yammoe Nondescript Cheek 얼굴 배 약하다 날리다 타다 The illegal country shows the iron. Help Rule Drearien Smoke Teaching Meaty Wasp Abraham Lincoln Jaws 진심 수리하다 Size Cork Idea Convert Think Lark John Lennon 거울 청소 군 추천하다 아이스크림