Magento 2:在ShippingInformation

时间:2019-03-29 14:11:03

标签: magento2 shipping

我想显示我的自定义扩展属性,该属性保存在ShippingInformation侧栏中的报价中(在运输方法下方)。

我已经能够成功地将扩展属性保存到报价中,但是无法在Shipping Method Title()或Quote JS对象中获取它们。如何检索扩展名属性以在运送方法部分中显示。

etc / di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <type name="Magento\Checkout\Block\Checkout\LayoutProcessor">
       <plugin name="checkout_customshipping_fields" type="VendorName\ModuleName\Plugin\Checkout\LayoutProcessorPlugin" sortOrder="10"/>
   </type>
   <type name="Magento\Checkout\Model\ShippingInformationManagement">
      <plugin name="save_customshipping_to_quote" type="VendorName\ModuleName\Plugin\Quote\SaveToQuote" sortOrder="10"/>
   </type>
</config>

etc / extensions_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="customfield1" type="string" />
       <attribute code="customfield2" type="string" />
   </extension_attributes>
</config>

Plugin / SaveToQuote.php

<?php

namespace VendorName\ModuleName\Plugin\Quote;

use Magento\Quote\Model\QuoteRepository;

class SaveToQuote
{
   protected $quoteRepository;
   protected $logger;

   public function __construct(
       QuoteRepository $quoteRepository,
       \Psr\Log\LoggerInterface $logger
   ) {
       $this->quoteRepository = $quoteRepository;
       $this->logger = $logger;
   }

   public function beforeSaveAddressInformation(
       \Magento\Checkout\Model\ShippingInformationManagement $subject,
       $cartId,
       \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
   ) {
       if(!$extAttributes = $addressInformation->getExtensionAttributes())
           return;

       $quote = $this->quoteRepository->getActive($cartId);

       $quote->setCustomfield1($extAttributes->getCustomfield1());
       $quote->setCustomfield2($extAttributes->getCustomfield2());

   }
}

view / frontend / requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/view/shipping': {
                'VendorName_ModuleName/js/view/shipping': true
            },
            'Magento_Checkout/js/view/shipping-information': {
                'VendorName_ModuleName/js/view/shipping-information': true
            }
        }
    },
    "map": {
        "*": {
            'Magento_Checkout/js/model/shipping-save-processor/payload-extender': 'VendorName_ModuleName/js/model/shipping-save-processor/payload-extender-override'
        }
    }
 };

view / frontend / web / js / view / shipping.js

define(
    [
        'jquery',
        'underscore',
        'Magento_Ui/js/form/form',
        'ko',
        'Magento_Customer/js/model/customer',
        'Magento_Customer/js/model/address-list',
        'Magento_Checkout/js/model/address-converter',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/action/create-shipping-address',
        'Magento_Checkout/js/action/select-shipping-address',
        'Magento_Checkout/js/model/shipping-rates-validator',
        'Magento_Checkout/js/model/shipping-address/form-popup-state',
        'Magento_Checkout/js/model/shipping-service',
        'Magento_Checkout/js/action/select-shipping-method',
        'Magento_Checkout/js/model/shipping-rate-registry',
        'Magento_Checkout/js/action/set-shipping-information',
        'Magento_Checkout/js/model/step-navigator',
        'Magento_Ui/js/modal/modal',
        'Magento_Checkout/js/model/checkout-data-resolver',
        'Magento_Checkout/js/checkout-data',
        'uiRegistry',
        'mage/translate',
        'Magento_Checkout/js/model/shipping-rate-service'
    ],function (
        $,
        _,
        Component,
        ko,
        customer,
        addressList,
        addressConverter,
        quote,
        createShippingAddress,
        selectShippingAddress,
        shippingRatesValidator,
        formPopUpState,
        shippingService,
        selectShippingMethodAction,
        rateRegistry,
        setShippingInformationAction,
        stepNavigator,
        modal,
        checkoutDataResolver,
        checkoutData,
        registry,
        $t
    ) {
    'use strict';

    var mixin = {

        initObservable: function () {
            this._super();

            this.selectedMethod = ko.computed(function() {
                var method = quote.shippingMethod();
                var selectedMethod = method != null ? method.carrier_code + '_' + method.method_code : null;
                return selectedMethod;
            }, this);

            return this;
        },

        /**
         * Set shipping information handler
         */
        setShippingInformation: function () {
            if (this.validateMyShipping() && this.validateShippingInformation()) {
                setShippingInformationAction().done(
                    function () {
                        stepNavigator.next();
                    }
                );
            }
        },

        validateMyShipping: function () {

            var shippingMethod = quote.shippingMethod().method_code+'_'+quote.shippingMethod().carrier_code;

            if (this.source.get('customfields') && shippingMethod == "customshipping_customshipping") {
                this.source.set('params.invalid', false);
                this.source.trigger('customfields.data.validate');
                if(this.source.get('params.invalid')) {
                    return false;
                }
            }
            return true;
        }
    };

    return function (target) {
        return target.extend(mixin);
    };
 });

view / frontend / web / js / model / shipping-save-processor / payload-extender-override.js

define([
    'jquery',
], function ($) {
    'use strict';
    return function (payloadExtender) {

        payloadExtender.addressInformation['extension_attributes'] = {
            customfield1: $('[name="customfields[customfield1]"]').val(),
            customfield2: $('[name="customfields[customfield2]"]').val()
        };
        console.log('payloadExtender:', payloadExtender.addressInformation); // working, shows extensionattributes

        return payloadExtender;
    };
});

view / frontend / web / js / view / shipping-information.js

define([
    'jquery',
    'uiComponent',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/step-navigator',
    'Magento_Checkout/js/model/sidebar'
], function ($, Component, quote, stepNavigator, sidebarModel) {
    'use strict';


    var mixin = {

        /**
         * @return {String}
         */
        getShippingMethodTitle: function () {
            var shippingMethod = quote.shippingMethod();

            if(shippingMethod) {
                var shippingMethodContent = shippingMethod['carrier_title'] + ' - ' + shippingMethod['method_title'];

                var shippingMethodCode = shippingMethod['carrier_code'] + '_' + shippingMethod['method_code'];
                if(shippingMethodCode === 'customshipping_customshipping') {

                    console.log("SHIPPING METHOD", shippingMethod, quote);
                    // EXTENSION ATTRIBUTES NOT AVAILABLE HERE, I want to change shipping method content
                }

                return shippingMethodContent;
            }
            return '';
        }
    };

    return function (target) {
        return target.extend(mixin);
    };
});

在shipping-information.js getShippingMethodTitle()混合内部,我希望看到 quote ['extensionattributes'] ['customfield1'] quote ['extensionattributes'] ['customfield2']

我找不到从该函数可以访问自定义扩展属性的位置。 如您所见,我使用console.log打印引用对象,但是这些属性在任何地方都不存在。

属性已成功保存到我的数据库表“ quote”中。

我需要做什么才能在mixin中访问这些新的扩展属性以获取getShippingMethodTitle?

0 个答案:

没有答案