0

I hope someone can help me :)

I would like to add a („House Number”) field for shipping and billing informations in Magento 2. I have successfully created the field, but when I submit a test order, this field will appear blank in the confirmation and not be saved anywhere. I've been searching for a lot on this topic, but I did not find any answer yet. I built the („House Number”) module with an online module generator, called Magento 2 module creator and code generator. I've attached the previous code in an attachment. It would be great if someone could help me with that. However, if someone assumes this issue as a job, please send a message.

\app\code\Magemod\view\frontend\web\js\model\shipping-save-processor\default.js

 define([
'ko',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/resource-url-manager',
'mage/storage',
'Magento_Checkout/js/model/payment-service',
'Magento_Checkout/js/model/payment/method-converter',
'Magento_Checkout/js/model/error-processor',
'Magento_Checkout/js/model/full-screen-loader',
'Magento_Checkout/js/action/select-billing-address',
'Magento_Checkout/js/model/shipping-save-processor/payload-extender'
], function (
ko,
quote,
resourceUrlManager,
storage,
paymentService,
methodConverter,
errorProcessor,
fullScreenLoader,
selectBillingAddressAction,
payloadExtender
) {
'use strict';

return {
    /**
     * @return {jQuery.Deferred}
     */
    saveShippingInformation: function () {
        var payload;

        //console.log(quote.shippingAddress());

        if (!quote.billingAddress()) {
            selectBillingAddressAction(quote.shippingAddress());
        }

        var haz ;
        require(['jquery', 'jquery/ui'], function($){
          jQuery(document).ready( function() {
            haz= $('[name="haz"]').val();

          });
        });         
        payload = {
                addressInformation: {
                    'shipping_address': quote.shippingAddress(),
                    'billing_address': quote.billingAddress(),
                'shipping_method_code': quote.shippingMethod()['method_code'],
                'shipping_carrier_code': quote.shippingMethod()['carrier_code'],
                   'extension_attributes':{                         
                        haz: haz
                    }  
                }
            };
        payloadExtender(payload);

        fullScreenLoader.startLoader();

        return storage.post(
            resourceUrlManager.getUrlForSetShippingInformation(quote),
            JSON.stringify(payload)
        ).done(
            function (response) {
                quote.setTotals(response.totals);
                paymentService.setPaymentMethods(methodConverter(response['payment_methods']));
                fullScreenLoader.stopLoader();
            }
        ).fail(
            function (response) {
                errorProcessor.process(response);
                fullScreenLoader.stopLoader();
            }
        );
    }
};
});

\app\code\Magemod\view\frontend\requirejs-config.js

var config = {
"map": {
    "*": {
        'Magento_Checkout/js/model/shipping-save-processor/default': 'Magemod_Haz/js/model/shipping-save-processor/default'
    }
}
};

\app\code\Magemod\Setup\InstallData.php

<?php
namespace Magemod\Haz\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
class InstallData implements InstallDataInterface
{

private $customerSetupFactory;

/**
 * Constructor
 *
 * @param \Magento\Customer\Setup\CustomerSetupFactory $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(\Magento\Customer\Model\Indexer\Address\AttributeProvider::ENTITY, 'haz', [
        'label' => 'Haz',
        'input' => 'text',
        'type' => 'varchar',
        'source' => '',
        'required' => true,
        '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', 'haz')
    ->addData(['used_in_forms' => [
            'adminhtml_customer_address',
            'customer_address_edit',
            'customer_register_address'
        ]
    ]);
    $attribute->save();
}
}

\app\code\Magemod\Plugin\Checkout\Model\Checkout\LayoutProcessor.php

<?php 
namespace Magemod\Haz\Plugin\Checkout\Model\Checkout;
class LayoutProcessor
{
/**
 * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
 * @param array $jsLayout
 * @return array
 */
public function afterProcess(
    \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
    array  $jsLayout
) {
    $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
    ['shippingAddress']['children']['shipping-address-fieldset']['children']['haz'] = [
        'component' => 'Magento_Ui/js/form/element/abstract',
        'config' => [
            'customScope' => 'shippingAddress',
            'template' => 'ui/form/field',
            'elementTmpl' => 'ui/form/element/input',
            'options' => [],
            'id' => 'haz'
        ],
        'dataScope' => 'shippingAddress.haz',
        'label' => 'Opt-In to our news letter',
        'provider' => 'checkoutProvider',
        'visible' => true,
        'validation' => [],
        'sortOrder' => 250,
        'id' => 'haz',
        'value'=>'haz'
    ];

    return $jsLayout;
}
}
?>

\app\code\Magemod\Model\Checkout\ShippingInformationManagementPlugin.php

<?php
namespace Magemod\Haz\Model\Checkout;
class ShippingInformationManagementPlugin
{

protected $quoteRepository;
protected $logger;

public function __construct(
    \Psr\Log\LoggerInterface $logger,
    \Magento\Quote\Model\QuoteRepository $quoteRepository
) {
    $this->_logger = $logger;
    $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
) {
    $extAttributes = $addressInformation->getExtensionAttributes();
    $haz = $extAttributes->getHaz();
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************$haz');        
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,$haz);     
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************$haz');        
    $postData = file_get_contents("php://input");//Get all param
    $postData = (array)json_decode($postData);//Decode all json param
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************$postData');       
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG, print_r($postData,true));     
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************/$postData');      

    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************');        
    //$this->_logger->log(\Psr\Log\LogLevel::DEBUG, print_r($extAttributes->Debug(),true));     
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG, print_r($addressInformation->Debug(),true));      

    $quote = $this->quoteRepository->getActive($cartId);
    $quote->setHaz('165');
    $postData = file_get_contents("php://input");//Get all param
    $postData = (array)json_decode($postData);//Decode all json param
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG, print_r($postData,true));
}
}

\app\code\Magemod\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="Magento\Checkout\Block\Checkout\LayoutProcessor">
        <plugin name="haz" type="Magemod\Haz\Plugin\Checkout\Model\Checkout\LayoutProcessor" sortOrder="100"/>
    </type>
</config>

\app\code\Magemod\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-in-quote" type="Magemod\Haz\Model\Checkout\ShippingInformationManagementPlugin" sortOrder="10"/>
</type>
</config>

\app\code\Magemod\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\Checkout\Api\Data\ShippingInformationInterface">
    <attribute code="haz" type="string"/>
</extension_attributes>
</config>

\app\code\Magemod\registration.php

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

\app\code\Magemod\composer.json

{
"name": "magemod/module-haz",
"description": "",
"type": "magento2-module",
"license": "proprietary",
"authors": [
    {
        "email": "info@mage2gen.com",
        "name": "Mage2Gen"
    }
],
"minimum-stability": "dev",
"require": {},
"autoload": {
    "psr-4": {
        "Magemod\\Haz\\": ""
    },
    "files": [
        "registration.php"
    ]
   }
}

\app\code\Magemod\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="Magemod_Haz" setup_version="1.0.0">
    <sequence>
        <module name="Magento_Customer"/>
    </sequence>
</module>
</config>
  • Do you want to use postNL as postNL already provide the house number in their extension. – Sukumar Gorai Nov 13 '18 at 13:11
0

Try adding the fieldset.xml file to your etc directory with the following content:

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="urn:magento:framework:DataObject/etc/fieldset.xsd">
       <scope id="global">
          <fieldset id="sales_convert_quote_address">
            <field name="haz">
               <aspect name="to_order" />
            </field>
         </fieldset>
      </scope>
</config>

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.