16

I have added the drop-down custom field on the checkout page with custom values. It's working fine also save attribute values in the database but not display in the order shipping address. Any idea how to show it?

enter image description here

InstallSchema.php

$connection->addColumn(
                $installer->getTable('quote_address'),
                'mob_type',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table ::TYPE_TEXT,
                    'nullable' => true,
                    'default' => NULL,
                    'length' => 255,
                    'comment' => 'Mob Type'
                ]
            );
        $connection->addColumn(
                $installer->getTable('sales_order_address'),
                'mob_type',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table ::TYPE_TEXT,
                    'nullable' => true,
                    'default' => NULL,
                    'length' => 255,
                    'comment' => 'Mob Type'
                ]
            );
        $installer->endSetup();

Plugin

use Magento\Checkout\Block\Checkout\LayoutProcessor;

class MobPlugin
{
    public function afterProcess(LayoutProcessor $subject, $jsLayout) {
        $customAttributeCode = 'mob_type';
        $customField = [
            'component' => 'Magento_Ui/js/form/element/select',
            'config' => [
                'customScope' => 'shippingAddress.custom_attributes',
                'template' => 'ui/form/field',
                'elementTmpl' => 'ui/form/element/select',
                'id' => 'drop-down',
            ],
            'dataScope' => 'shippingAddress.custom_attributes.mob_type',
            'label' => 'Mob Type',
            'provider' => 'checkoutProvider',
            'visible' => true,
            'validation' => ['required-entry' => true],
            'sortOrder' => 150,
            'id' => 'drop-down',
            'options' => [
                [
                    'value' => 'local',
                    'label' => 'Local',
                ],
                [
                    'value' => 'vip',
                    'label' => 'VIP',
                ]
            ]
        ];

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

        return $jsLayout;
    }
}

enter image description here

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\Model\ShippingInformationManagement">
        <plugin name="save_custom_field" type="Namespace\CustomModule\Plugin\Checkout\SaveAddressInformation" />
    </type>

</config>

SaveAddressInformation.php

class SaveAddressInformation
{
    protected $quoteRepository;
    public function __construct(
        \Magento\Quote\Model\QuoteRepository $quoteRepository
    ) {
        $this->quoteRepository = $quoteRepository;
    }
    /**
     * @param \Magento\Checkout\Model\ShippingInformationManagement $subject
     * @param $cartId
     * @param \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
     */
    public function beforeSaveAddressInformation(
        \Magento\Checkout\Model\ShippingInformationManagement $subject,
        $cartId,
        \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
    ) {
        $shippingAddress = $addressInformation->getShippingAddress();
    $shippingAddressExtensionAttributes = $shippingAddress->getExtensionAttributes();
    if ($shippingAddressExtensionAttributes) {
        $customField = $shippingAddressExtensionAttributes->getMobType();
        $shippingAddress->setMobType($customField);
    }

    }
}

enter image description here Refe Extension

Above plugin is working fine and save values in the quote_address table. I want to display custom attribute in order view page and email template also.anyone have an idea what's wrong with the code. Thanks in advance

8
6
+50

Navigate to System Configuration

Stores -> Configuration -> Customers -> Customer Configuration -> Address Templates

From Address Templates, Find HTML section, untick checkbox system value, add following code. you may change an attribute code if need.

For the email template, same address format [HTML Address format] will work.

{{depend mob_type}}Mob_Type: {{var mob_type}}{{/depend}}

Run php bin/magento cache:clean if not shows.

An attribute will show at the order view page and order email also.

above is displayed in both address but if you want only show in shipping then you need to put only SMS value in shipping address table (sales_order_address and quote_address) not billing it's working fine. Enjoy

Table view -

enter image description here

Result -

enter image description here

5
  • how can I save only in shipping address? Mar 10 '18 at 9:55
  • you need to add the event. or this one may be usefull - magento.stackexchange.com/questions/138902/… Mar 10 '18 at 9:58
  • Actually it not works for my case, i don't understand how a variable can refer to extension attrbute which already was saved in quote_address & sales_order_address table. Seems i need to override the two info.phtml template
    – hkguile
    Feb 13 '20 at 9:48
  • @hkguile can you please post your solution?
    – Ekta Puri
    Dec 11 '20 at 0:34
  • Just in case anyone having issues dispkaying value in sales order view: Plugin works well, but solution to display it in admin order page did not worked for me, so I added sales/order/view/info.phtml in my Vendor/Module folder and added <?php $add = $order->getShippingAddress();echo "Mob Type: ".$add->getMobType()?> it display the value in sales order page
    – Ekta Puri
    Dec 14 '20 at 21:44
4

Try with my approach. Taking into consideration module as described in the question.

  1. Used the same module showing in the question. no change

  2. Installed reference extension which you are referring (SMS extension)

Navigate to System Configuration

Stores -> Configuration -> Customers -> Customer Configuration -> Address Templates

From Address Templates, Find HTML section, untick checkbox system value, add following code. you may change an attribute code if need.

For email template, same address format [HTML Address format] will work.

{{depend mob_type}}Mob_Type: {{var mob_type}}{{/depend}}

enter image description here

may be required to clear cache.

Run php bin/magento cache:clean if not shows

An attribute will show at the order view page and order email also.

enter image description here

6
  • Thank you for your answer. how we manage display only in shipping address area? Mar 10 '18 at 6:46
  • you may have to create more system configuration, for shipping address only as html_for_shipping. Magento/sales/view/adminhtml/templates/order/view/info.phtml, find below line $block->getFormattedAddress( $order->getShippingAddress() ); change to $block->getFormattedShippingAddress( $order->getShippingAddress() ); In info.php file, you may create new method only for shipping address formatting. You can change parameter of format method 'html' to 'html_for_shipping', where 'html_for_shipping' will be your new system configuration value for shipping address format.
    – sandip
    Mar 10 '18 at 7:02
  • suddenly it's not working. not display me above SMS details in order. any idea? Mar 28 '18 at 7:29
  • I tried this @sandip..But it does not get displayed....Please help me Oct 13 '18 at 10:24
  • not working for me, value saved in db table but not showing in backend
    – Ekta Puri
    Dec 11 '20 at 0:28
3

If the attribute is saved correctly you need to add the attribute to address templates. These can be found in

Stores -> Configuration -> Customers -> Customer Configuration -> Address Templates

You can add at the end something like:

{{depend mob_type}}, Mob. Type: {{var mob_type}}{{/depend}}

Depending on the template type, you can use <br/> to create new lines.

5
  • I want to display only shipping address and how I can manage also on order view page? Mar 9 '18 at 13:18
  • These templates are used everywhere. Frontend, backend, pdf, emails ... If the attribute is saved only in shipping address then it will only display there
    – Langley
    Mar 9 '18 at 13:21
  • ok, let me check it Mar 9 '18 at 13:23
  • Not working. not display anywhere. -nimb.ws/9cnpHW Mar 9 '18 at 13:36
  • Hi @Langley Thanks for the answer, iam getting this only in billing address not displaying it in shipping address, i want to display it in both places. May 25 '18 at 6:50
2

I would do that like this: add it to the quote and sales_orderand work the data from there use the following code ( also try using UpgradeSchema scripts if you need to update existing DB table, InstallSchema should be used for new DB tables )

namespace Vendor\Module\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class UpgradeSchema implements UpgradeSchemaInterface
{
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $quoteAddressTable = 'quote';
        $orderTable = 'sales_order';

        //Quote address table
        $setup->getConnection()
            ->addColumn(
                $setup->getTable($quoteAddressTable),
                'mob_type',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'comment' =>'Mob type'
                ]
            );
        //Order address table
        $setup->getConnection()
            ->addColumn(
                $setup->getTable($orderTable),
                'mob_type',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'comment' =>'Mob type'

                ]
            );

        $setup->endSetup();
    }
}

UPDATE

Create a mixin js as follows:

in requirejs-config.js

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

the 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();
        });
    };
});

Also you should have a extension_attributes.xml in Your_Module/etc/ with following code

<?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>

make changes where needed ( attribute code, type, etc. this will add your custom attribute to the shipping information

6
  • but how to save this field data in the table can you please share code? thanks Mar 7 '18 at 14:17
  • can you show me how you defined your plugin in the di.xml file?
    – Vlad Patru
    Mar 7 '18 at 14:59
  • check I updated save field code and working fine but how to display in order shipping address area? Mar 7 '18 at 19:11
  • thanks for the update but look my above question. save things done but not display on the order view and email template. thanks Mar 9 '18 at 13:20
  • the fields there are show with the getShippingAddress() function that gets all the fields set to the address itself, thats why I added this code , it should add your attribute to the shipping address itself
    – Vlad Patru
    Mar 9 '18 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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