magento2 如何在地址表单中添加新字段

在Magento 2的默认结帐表单中,您可以添加新的字段,例如送货地址和帐单地址表单。在今天的帖子中,我将向您展示如何在地址表单中添加新字段的五个简单步骤。

如何在地址表单中添加新字段

  • 第1步:向布局添加字段
  • 第2步:添加JS mixin以修改数据提交
  • 第3步:加载mixin
  • 第4步:向地址模型添加字段
  • 步骤5:访问服务器端的自定义字段值

第1步:向布局添加字段

由于发货地址和帐单地址表单都是动态创建的,要自定义其布局,您需要为该方法创建一个插件\Magento\Checkout\Block\Checkout\LayoutProcessor::process,然后di.xml在模块中的文件中声明它。

以下是将自定义属性字段添加到送货地址表单的示例代码:

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

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

在此示例中,该字段将添加到customAttributes属性中Magento_Checkout/js/model/new-customer-address.js,该属性是一个JavaScript对象,列出所有预定义的地址属性并匹配相应的服务器端接口\Magento\Quote\Api\Data\AddressInterface

customAttributes属性与该方法有关\Magento\Quote\Model\Quote\Address\CustomAttributeListInterface::getAttributes。此外,它旨在保存自定义EAV地址属性。我刚才提供的示例代码将帮助您自动处理前端的存储持久性。

但是,不是添加插件,还有另一种方法是使用依赖注入,也称为DI。要使用DI,您需要LayoutProcessor添加将自定义字段添加到地址表单类的目录<your_module_dir>/Block/Checkout/。该\Magento\Checkout\Block\Checkout\LayoutProcessorInterface接口必须由类实现。代码示例可以用作方法实现的示例\Magento\Checkout\Block\Checkout\LayoutProcessorInterface::process()

对于LayoutProcessor要添加到处理器的相应池类,你需要指定以下代码(在这里,你需要更换%unique_name%,并%path\to\your\LayoutProcessor%通过你的真实值)的<your_module_dir>/etc/frontend/di.xml文件:

<type name="Magento\Checkout\Block\Onepage">
        <arguments>
            <argument name="layoutProcessors" xsi:type="array">
                <item name="%unique_name%" xsi:type="object">%path\to\your\LayoutProcessor%</item>
            </argument>
        </arguments>
</type>

第2步:添加JS mixin以修改数据提交

要更改组件负责人的数据提交行为,请将JS mixin添加到服务器端。

首先,在自定义模块中,您需要将mixin定义为一个单独的AMD模块,它返回一个回调函数。mixin文件只要在<your_module_dir>/view/frontend/web目录中就可以添加到任何地方。您也可以根据需要自由命名文件。

下面是一个示例mixin代码,用于修改其Magento_Checkout/js/action/set-shipping-information行为。该组件负责在两个运输和计费步骤之间提交数据:

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

当字段添加到帐单地址表单时,Magento_Checkout/js/action/place-order or Magento_Checkout/js/action/set-payment-information component需要根据您需要将自定义字段值传递到服务器端的时间来修改其行为。

如果你想查看它修改一个组件的混合的例子,请查看地方阶mixin.js这是在Magento_CheckoutAgreements模块。

第3步:加载mixin

通过添加requirejs-config.js<YourModule_dir>/view/frontend/目录,您将能够告诉Magento为相应的JS组件加载mixin。

下面是一个使用之前添加的样本mixin的示例:

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

第4步:向地址模型添加字段

在此阶段,您需要extension_attributes.xml<YourModule_dir>/etc/目录中添加该文件,以便将字段添加到服务器端的地址模型。

以下是extension_attributes.xml文件的示例:

<?xml version="1.0"?>

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

记得在运行命令var/generation时清除目录setup:di:compile。您将能够在中添加新的getter和setter方法file /var/generation/Magento/Quote/Api/Data/AddressInterface.php

步骤5:访问服务器端的自定义字段值

完成上一节中提到的所有步骤后,将生成包含您的自定义属性的界面,您将能够访问您的字段值。

创建Magento/Quote/Api/Data/AddressInterface.php接口实例时,也可以设置或获取这些属性值。

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$addressInformation = $objectManager->create('Magento\Checkout\Api\Data\ShippingInformationInterface');
$extAttributes = $addressInformation->getExtensionAttributes();
$selectedShipping = $extAttributes->getCustomShippingCharge(); //get custom attribute data.

结论

以上是五个步骤,可以帮助您以地址形式添加新字段。我希望在管理地址表单时,本教程对您有所帮助。如果您有任何问题或新想法,请随时在下面发表评论。

赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论