如何在Magento2的“结帐”页面中添加自定义字段


Answers:


23

今天,我将解释如何在结帐页面的所有步骤中添加自定义字段,并在下订单后将其保存,以及下订单后如何使用已过帐的数据

第一个字段 delivery_date:-客户将在发货步骤的交货日期提及

第二字段订单注释:-将进入付款步骤,下订单后,此注释将添加到订单注释历史记录中

步骤1:-确保在所有需要的表(如报价单)中sales_order以及sales_order_grid通过安装或升级脚本添加了delivery_date

<?php

namespace Sugarcode\Deliverydate\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallSchema implements InstallSchemaInterface
{

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        $installer->getConnection()->addColumn(
            $installer->getTable('quote'),
            'delivery_date',
            [
                'type' => 'datetime',
                'nullable' => false,
                'comment' => 'Delivery Date',
            ]
        );

        $installer->getConnection()->addColumn(
            $installer->getTable('sales_order'),
            'delivery_date',
            [
                'type' => 'datetime',
                'nullable' => false,
                'comment' => 'Delivery Date',
            ]
        );

        $installer->getConnection()->addColumn(
            $installer->getTable('sales_order_grid'),
            'delivery_date',
            [
                'type' => 'datetime',
                'nullable' => false,
                'comment' => 'Delivery Date',
            ]
        );

        $setup->endSetup();
    }
}

步骤2:-在运输和付款步骤中添加自定义字段,我们可以通过两种方式实现一种layout xml,另一种是插件,以下是通过插件添加字段的方式

我们di.xml在模块中创建一个文件-Sugarcode/Deliverydate/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="add-delivery-date-field"
                type="Sugarcode\Deliverydate\Model\Checkout\LayoutProcessorPlugin" sortOrder="10"/>
    </type>
</config>

Sugarcode \ Plugin \ Checkout \ LayoutProcessor.php

<?php
namespace Sugarcode\Plugin\Checkout;


class LayoutProcessor
{

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $checkoutSession;

    /**
     * @var \Magento\Customer\Model\AddressFactory
     */
    protected $customerAddressFactory;

    /**
     * @var \Magento\Framework\Data\Form\FormKey
     */
    protected $formKey;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory $agreementCollectionFactory,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Customer\Model\AddressFactory $customerAddressFactory
    ) {
        $this->scopeConfig = $context->getScopeConfig();
        $this->checkoutSession = $checkoutSession;
        $this->customerAddressFactory = $customerAddressFactory;
    }
    /**
     * @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']['before-form']['children']['delivery_date'] = [
             'component' => 'Magento_Ui/js/form/element/abstract',
            'config' => [
                'customScope' => 'shippingAddress',
                'template' => 'ui/form/field',
                'elementTmpl' => 'ui/form/element/date',
                'options' => [],
                'id' => 'delivery-date'
            ],
            'dataScope' => 'shippingAddress.delivery_date',
            'label' => 'Delivery Date',
            'provider' => 'checkoutProvider',
            'visible' => true,
            'validation' => [],
            'sortOrder' => 200,
            'id' => 'delivery-date'
        ];


            $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
            ['payment']['children']['payments-list']['children']['before-place-order']['children']['comment'] = [
                'component' => 'Magento_Ui/js/form/element/textarea',
                'config' => [
                    'customScope' => 'shippingAddress',
                    'template' => 'ui/form/field',
                    'options' => [],
                    'id' => 'comment'
                ],
                'dataScope' => 'ordercomment.comment',
                'label' => 'Order Comment',
                'notice' => __('Comments'),
                'provider' => 'checkoutProvider',
                'visible' => true,
                'sortOrder' => 250,
                'id' => 'comment'
            ];

        return $jsLayout;
    }


}

现在所有字段都在checkout页面中,现在如何保存数据

与M2中的M1不同,所有Checkout页面都是完全剔除JS和API

我们有两个步骤,第一步是运输,第二步是付款,我们需要保存两个字段

以下是保存送货地址后如何保存数据的方法

运送步骤

在M2使用中保存运输信息

app/code/Magento/Checkout/view/frontend/web/js/model/shipping-save-processor/default.js

准备json和调用,api所以我们需要重写此js,并且php会发生边保存

\ Magento \ Checkout \ Model \ ShippingInformationManagement :: SaveAddressInformation()和ShippingInformationManagement由Magento \ Checkout \ Api \ Data \ ShippingInformationInterface实现

M2有一个强大的概念,称为M2 extension_attributes ,用于将数据动态存储到核心表中。

步骤3:-建立档案Deliverydate/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="delivery_date" type="string"/>
    </extension_attributes>
    <extension_attributes for="Magento\Quote\Api\Data\PaymentInterface">
        <attribute code="comment" type="string"/>
    </extension_attributes>
</config>

覆盖js创建一个js文件,Deliverydate/view/frontend/requirejs-config.js 我们需要使用mixns

var config = {
config: {
    mixins: {
        'Magento_Checkout/js/action/place-order': {
            'Sugarcode_Deliverydate/js/order/place-order-mixin': true
        },
        'Magento_Checkout/js/action/set-payment-information': {
            'Sugarcode_Deliverydate/js/order/set-payment-information-mixin': true
        },
        'Magento_Checkout/js/action/set-shipping-information': {
            'Sugarcode_Deliverydate/js/order/set-shipping-information-mixin': true
        }
    }
};

js / order / set-shipping-information-mixin.js delivery_date

/**
 * @author aakimov
 */
/*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'] = {};
            }

            // you can extract value of extension attribute from any place (in this example I use customAttributes approach)
            shippingAddress['extension_attributes']['delivery_date'] = jQuery('[name="delivery_date"]').val();
            // pass execution to original action ('Magento_Checkout/js/action/set-shipping-information')
            return originalAction();
        });
    };
});

下一步是将此自定义字段发布数据保存到报价单中。让我们通过在我们的XML节点中添加一个xml节点来制作另一个插件etc/di.xml

<type name="Magento\Checkout\Model\ShippingInformationManagement">
        <plugin name="save-in-quote" type="Sugarcode\Deliverydate\Plugin\Checkout\ShippingInformationManagementPlugin" sortOrder="10"/>
</type>

创建一个文件Sugarcode \ Deliverydate \ Plugin \ Checkout \ ShippingInformationManagementPlugin.php

<?php

namespace Sugarcode\Deliverydate\Plugin\Checkout;

class ShippingInformationManagementPlugin
{

    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
    ) {
        $extAttributes = $addressInformation->getShippingAddress()->getExtensionAttributes();
        $deliveryDate = $extAttributes->getDeliveryDate();
        $quote = $this->quoteRepository->getActive($cartId);
        $quote->setDeliveryDate($deliveryDate);
    }
}

转到付款步骤后不久,数据将保存在报价表中

为了在下订单后保存相同的数据,我们需要使用fieldset

等/fieldset.xml

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

现在让我们保存付款步骤字段

如果我们在付款步骤中有额外的字段,并且需要发布该数据,则需要像在运输步骤中那样覆盖其他js

就像运送信息一样,我们有付款信息

ww可以通过覆盖实现Magento_Checkout/js/action/place-order.js (但是启用协议时会出现问题,因此我们需要使用re提到的mixins)

Sugarcode_Deliverydate/js/order/place-order-mixin.js


/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define([
    'jquery',
    'mage/utils/wrapper',
    'Sugarcode_Deliverydate/js/order/ordercomment-assigner'
], function ($, wrapper, ordercommentAssigner) {
    'use strict';

    return function (placeOrderAction) {

        /** Override default place order action and add comments to request */
        return wrapper.wrap(placeOrderAction, function (originalAction, paymentData, messageContainer) {
            ordercommentAssigner(paymentData);

            return originalAction(paymentData, messageContainer);
        });
    };
});

Sugarcode_Deliverydate / js / order / ordercomment-assigner.js

/*jshint browser:true jquery:true*/
/*global alert*/
define([
    'jquery'
], function ($) {
    'use strict';


    /** Override default place order action and add comment to request */
    return function (paymentData) {

        if (paymentData['extension_attributes'] === undefined) {
            paymentData['extension_attributes'] = {};
        }

        paymentData['extension_attributes']['comment'] = jQuery('[name="ordercomment[comment]"]').val();
    };
});

Sugarcode_Deliverydate / js / order / set-payment-information-mixin.js

/*jshint browser:true jquery:true*/
/*global alert*/
define([
    'jquery',
    'mage/utils/wrapper',
    'Sugarcode_Deliverydate/js/order/ordercomment-assigner'
], function ($, wrapper, ordercommentAssigner) {
    'use strict';

    return function (placeOrderAction) {

        /** Override place-order-mixin for set-payment-information action as they differs only by method signature */
        return wrapper.wrap(placeOrderAction, function (originalAction, messageContainer, paymentData) {
            ordercommentAssigner(paymentData);

            return originalAction(messageContainer, paymentData);
        });
    };
});

并需要为创建一个插件 Magento\Checkout\Model\PaymentInformationManagement

所以在etc/di下面的代码中添加

 <type name="Magento\Checkout\Model\PaymentInformationManagement">
        <plugin name="order_comments_save-in-order" type="Sugarcode\Deliverydate\Plugin\Checkout\PaymentInformationManagementPlugin" sortOrder="10"/>
    </type>

然后创建一个文件 Sugarcode\Deliverydate\Plugin\Checkout\PaymentInformationManagementPlugin.php

/**
 * One page checkout processing model
 */
class PaymentInformationManagementPlugin
{

    protected $orderRepository;

    public function __construct(
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
    ) {
        $this->orderRepository = $orderRepository;
    }


    public function aroundSavePaymentInformationAndPlaceOrder(
        \Magento\Checkout\Model\PaymentInformationManagement $subject,
        \Closure $proceed,
        $cartId,
        \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
        \Magento\Quote\Api\Data\AddressInterface $billingAddress = null
    ) {
        $result = $proceed($cartId, $paymentMethod, $billingAddress);

         if($result){

            $orderComment =$paymentMethod->getExtensionAttributes();
             if ($orderComment->getComment())
               $comment = trim($orderComment->getComment());
           else
               $comment = ''; 


            $history = $order->addStatusHistoryComment($comment);
            $history->save();
            $order->setCustomerNote($comment);                
         }

        return $result;
    }
}

注意:-如果付款步骤中的字段需要保存在报价表中,则使用beofore插件执行相同的功能,并按照ShippingInformationManagementPlugin中的说明进行操作


请参考第1步,该文件应驻留在哪里?以及如何执行?由于只需要一次。
阿卜杜勒·莫伊兹

并且您确定这会在我的自定义步骤中添加表单有效,因为您在结帐步骤中引用了magento的构建。
阿卜杜勒·莫伊兹

Sugarcode / Deliverydate \ Setup:-在应用程序/代码文件夹中,FYI Sugarcode:-名称空间,Deliverydate模块名称和设置文件夹在Deliverydate内部,如何在运行upgrade命令中安装,如果您不知道upgrade命令,那么我觉得您很新在M2中,所以请通过基本m2
Pradeep Kumar

谢谢,我如何修改它以在新步骤上添加表单。我已经添加了?
阿卜杜勒·莫伊兹

如果将所有新步骤(如运输和付款步骤)加在一起,则需要检查以创建新票证或问题
Pradeep Kumar

1

在进行自定义之前,请执行以下操作。

  • 将Magento设置为开发人员模式
  • 不要编辑默认的Magento代码,而是在单独的模块中添加自定义项
  • 不要将Ui用作您的自定义模块名称

步骤1:创建表单UI组件的JS实现

<your_module_dir>/view/frontend/web/js/view/目录中,创建一个实现表单的.js文件。

/*global define*/
define([
    'Magento_Ui/js/form/form'
], function(Component) {
    'use strict';
    return Component.extend({
        initialize: function () {
            this._super();
            // component initialization logic
            return this;
        },

        /**
         * Form submit handler
         *
         * This method can have any name.
         */
        onSubmit: function() {
            // trigger form validation
            this.source.set('params.invalid', false);
            this.source.trigger('customCheckoutForm.data.validate');

            // verify that form data is valid
            if (!this.source.get('params.invalid')) {
                // data is retrieved from data provider by value of the customScope property
                var formData = this.source.get('customCheckoutForm');
                // do something with form data
                console.dir(formData);
            }
        }
    });
});

步骤2:建立HTML范本

knockout.js<your_module_dir>/view/frontend/web/template目录下为表单组件添加HTML模板。

例:

<div>
    <form id="custom-checkout-form" class="form" data-bind="attr: {'data-hasrequired': $t('* Required Fields')}">
        <fieldset class="fieldset">
            <legend data-bind="i18n: 'Custom Checkout Form'"></legend>
            <!-- ko foreach: getRegion('custom-checkout-form-fields') -->
            <!-- ko template: getTemplate() --><!-- /ko -->
            <!--/ko-->
        </fieldset>
        <button type="reset">
            <span data-bind="i18n: 'Reset'"></span>
        </button>
        <button type="button" data-bind="click: onSubmit" class="action">
            <span data-bind="i18n: 'Submit'"></span>
        </button>
    </form>
</div>

修改后清除文件

如果您将自定义.html模板应用于商店页面后对其进行了修改,则在您执行以下操作之前,所做的更改将不适用:

删除pub/static/frontendvar/view_preprocessed目录中的所有文件。重新加载页面。

步骤3:在结帐页面布局中声明表单

要将内容添加到“运输信息”步骤,请在中创建checkout_index_index.xml布局更新<your_module_dir>/view/frontend/layout/

它应该类似于以下内容。

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.root">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="checkout" xsi:type="array">
                            <item name="children" xsi:type="array">
                                <item name="steps" xsi:type="array">
                                    <item name="children" xsi:type="array">
                                        <item name="shipping-step" xsi:type="array">
                                            <item name="children" xsi:type="array">
                                                <item name="shippingAddress" xsi:type="array">
                                                    <item name="children" xsi:type="array">
                                                        <item name="before-form" xsi:type="array">
                                                            <item name="children" xsi:type="array">
                                                                <!-- Your form declaration here -->
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

静态形式:

下面的代码示例显示了包含四个字段的表单配置:文本输入,选择,复选框和日期。此表单使用在Magento_Checkout模块中引入的结帐数据提供程序(checkoutProvider):

<item name="custom-checkout-form-container" xsi:type="array">
    <item name="component" xsi:type="string">%your_module_dir%/js/view/custom-checkout-form</item>
    <item name="provider" xsi:type="string">checkoutProvider</item>
    <item name="config" xsi:type="array">
        <item name="template" xsi:type="string">%your_module_dir%/custom-checkout-form</item>
    </item>
    <item name="children" xsi:type="array">
        <item name="custom-checkout-form-fieldset" xsi:type="array">
            <!-- uiComponent is used as a wrapper for form fields (its template will render all children as a list) -->
            <item name="component" xsi:type="string">uiComponent</item>
            <!-- the following display area is used in template (see below) -->
            <item name="displayArea" xsi:type="string">custom-checkout-form-fields</item>
            <item name="children" xsi:type="array">
                <item name="text_field" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/abstract</item>
                    <item name="config" xsi:type="array">
                        <!-- customScope is used to group elements within a single form (e.g. they can be validated separately) -->
                        <item name="customScope" xsi:type="string">customCheckoutForm</item>
                        <item name="template" xsi:type="string">ui/form/field</item>
                        <item name="elementTmpl" xsi:type="string">ui/form/element/input</item>
                    </item>
                    <item name="provider" xsi:type="string">checkoutProvider</item>
                    <item name="dataScope" xsi:type="string">customCheckoutForm.text_field</item>
                    <item name="label" xsi:type="string">Text Field</item>
                    <item name="sortOrder" xsi:type="string">1</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="string">true</item>
                    </item>
                </item>
                <item name="checkbox_field" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/boolean</item>
                    <item name="config" xsi:type="array">
                        <!--customScope is used to group elements within a single form (e.g. they can be validated separately)-->
                        <item name="customScope" xsi:type="string">customCheckoutForm</item>
                        <item name="template" xsi:type="string">ui/form/field</item>
                        <item name="elementTmpl" xsi:type="string">ui/form/element/checkbox</item>
                    </item>
                    <item name="provider" xsi:type="string">checkoutProvider</item>
                    <item name="dataScope" xsi:type="string">customCheckoutForm.checkbox_field</item>
                    <item name="label" xsi:type="string">Checkbox Field</item>
                    <item name="sortOrder" xsi:type="string">3</item>
                </item>
                <item name="select_field" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/select</item>
                    <item name="config" xsi:type="array">
                        <!--customScope is used to group elements within a single form (e.g. they can be validated separately)-->
                        <item name="customScope" xsi:type="string">customCheckoutForm</item>
                        <item name="template" xsi:type="string">ui/form/field</item>
                        <item name="elementTmpl" xsi:type="string">ui/form/element/select</item>
                    </item>
                    <item name="options" xsi:type="array">
                        <item name="0" xsi:type="array">
                            <item name="label" xsi:type="string">Please select value</item>
                            <item name="value" xsi:type="string"></item>
                        </item>
                        <item name="1" xsi:type="array">
                            <item name="label" xsi:type="string">Value 1</item>
                            <item name="value" xsi:type="string">value_1</item>
                        </item>
                        <item name="2" xsi:type="array">
                            <item name="label" xsi:type="string">Value 2</item>
                            <item name="value" xsi:type="string">value_2</item>
                        </item>
                    </item>
                    <!-- value element allows to specify default value of the form field -->
                    <item name="value" xsi:type="string">value_2</item>
                    <item name="provider" xsi:type="string">checkoutProvider</item>
                    <item name="dataScope" xsi:type="string">customCheckoutForm.select_field</item>
                    <item name="label" xsi:type="string">Select Field</item>
                    <item name="sortOrder" xsi:type="string">2</item>
                </item>
                <item name="date_field" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/date</item>
                    <item name="config" xsi:type="array">
                        <!--customScope is used to group elements within a single form (e.g. they can be validated separately)-->
                        <item name="customScope" xsi:type="string">customCheckoutForm</item>
                        <item name="template" xsi:type="string">ui/form/field</item>
                        <item name="elementTmpl" xsi:type="string">ui/form/element/date</item>
                    </item>
                    <item name="provider" xsi:type="string">checkoutProvider</item>
                    <item name="dataScope" xsi:type="string">customCheckoutForm.date_field</item>
                    <item name="label" xsi:type="string">Date Field</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="string">true</item>
                    </item>
                </item>
            </item>
        </item>
    </item>
</item>

希望这可以帮助。


您添加了静态表单代码,它的文件名是什么以及它将放置在哪里?
Sanaullah Ahmad

@SanaullahAhmad有一个简单的方法太即使用一个模块,像这一个
亨利·罗杰
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.