Saya perlu menambahkan dua bidang khusus di setiap langkah pengiriman dan pembayaran halaman checkout di Magento 2 dan juga data harus disimpan dalam tabel yang diperlukan
bagaimana cara melakukannya di Magento 2
Saya perlu menambahkan dua bidang khusus di setiap langkah pengiriman dan pembayaran halaman checkout di Magento 2 dan juga data harus disimpan dalam tabel yang diperlukan
bagaimana cara melakukannya di Magento 2
Jawaban:
Hari ini saya akan menjelaskan cara menambahkan bidang khusus ke semua langkah halaman checkout dan menyimpannya setelah pesanan ditempatkan dan juga bagaimana menggunakan data yang diposting setelah melakukan pemesanan
Bidang ke-1 delivery_date
: - tempat pelanggan akan menyebutkan tanggal pengiriman dalam langkah pengiriman
Komentar bidang ke-2 : - akan berada di langkah Pembayaran dan setelah melakukan pemesanan, komentar ini akan ditambahkan ke riwayat komentar pesanan
Langkah 1 : - pastikan delivery_date ditambahkan di semua tabel kebutuhan seperti kutipan, sales_order
dan sales_order_grid
melalui skrip install atau upgrade
<?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();
}
}
Langkah 2 : - Menambahkan bidang khusus dalam langkah-langkah pengiriman dan pembayaran, kita dapat mencapainya dengan dua cara, satu layout xml
dan lainnya adalah plugin di bawah ini adalah cara bagaimana menambahkan bidang melalui plugin
Kami membuat di.xml
file di modul kami -Sugarcode/Deliverydate/etc/frontend/di.xml
Kami menggunakan area frontend agar tetap bersih, plugin kami harus berjalan hanya di frontend.
<?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;
}
}
Sekarang semua bidang ada di halaman checkout, sekarang bagaimana cara menyimpan data
tidak seperti M1 di M2 semua halaman Checkout sepenuhnya knockout JS dan API
Kami memiliki dua langkah, yang pertama adalah pengiriman dan langkah kedua adalah pembayaran di mana kami harus menyimpan kedua bidang
Di bawah ini adalah cara menyimpan data setelah alamat pengiriman disimpan
Langkah Pengiriman
Untuk menyimpan informasi pengiriman dalam penggunaan M2
app/code/Magento/Checkout/view/frontend/web/js/model/shipping-save-processor/default.js
untuk mempersiapkan json
dan memanggil api
sehingga kita perlu mengganti js ini dan selain itu php
akan terjadi
\ Magento \ Checkout \ Model \ ShippingInformationManagement :: SaveAddressInformation () dan ShippingInformationManagement dilaksanakan oleh Magento \ Checkout \ Api \ Data \ ShippingInformationInterface
M2 memiliki satu konsep kuat yang disebut extension_attributes
yang digunakan untuk data dinamis ke tabel inti memungkinkan menggunakannya
langkah 3 : - buat fileDeliverydate/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>
untuk mengganti js membuat file js Deliverydate/view/frontend/requirejs-config.js
kita perlu menggunakan 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();
});
};
});
Langkah selanjutnya adalah menyimpan data posting bidang khusus ini ke dalam kutipan. Mari kita membuat plugin lain dengan menambahkan simpul xml dietc/di.xml
<type name="Magento\Checkout\Model\ShippingInformationManagement">
<plugin name="save-in-quote" type="Sugarcode\Deliverydate\Plugin\Checkout\ShippingInformationManagementPlugin" sortOrder="10"/>
</type>
Buat file 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);
}
}
segera setelah Anda pindah ke langkah-langkah pembayaran data akan disimpan di tabel penawaran
untuk menyimpan data yang sama setelah melakukan pemesanan, kita perlu menggunakan fieldset
dll / 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>
Sekarang mari Simpan bidang langkah pembayaran
jika kita memiliki bidang tambahan dalam langkah pembayaran dan kita perlu memposting data itu maka kita perlu mengganti js lainnya seperti yang kita lakukan untuk langkah pengiriman
seperti informasi pengiriman, kami memiliki informasi pembayaran
ww dapat mencapai dengan menimpa adalah Magento_Checkout/js/action/place-order.js
(tetapi itu akan memiliki masalah ketika perjanjian diaktifkan sehingga kita perlu menggunakan mixin sebagaimana disebutkan dalam kembali)
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);
});
};
});
dan perlu membuat plugin untuk Magento\Checkout\Model\PaymentInformationManagement
jadi di etc/di
tambahkan kode di bawah ini
<type name="Magento\Checkout\Model\PaymentInformationManagement">
<plugin name="order_comments_save-in-order" type="Sugarcode\Deliverydate\Plugin\Checkout\PaymentInformationManagementPlugin" sortOrder="10"/>
</type>
lalu buat file 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;
}
}
Catatan: - jika bidang dalam langkah pembayaran perlu disimpan dalam tabel kutipan maka gunakan plugin beofore untuk fungsi yang sama dan ikuti seperti yang dilakukan dalam ShippingInformationManagementPlugin
Sebelum melakukan penyesuaian, lakukan hal berikut.
Langkah 1: Buat implementasi JS dari komponen UI bentuk
Di <your_module_dir>/view/frontend/web/js/view/
direktori Anda , buat file .js yang mengimplementasikan formulir.
/*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);
}
}
});
});
Langkah 2: Buat template HTML
Tambahkan knockout.js
templat HTML untuk komponen formulir di bawah <your_module_dir>/view/frontend/web/
direktori templat.
Contoh:
<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>
Hapus file setelah modifikasi
Jika Anda memodifikasi template .html kustom Anda setelah diterapkan pada halaman toko, perubahan tidak akan berlaku hingga Anda melakukan hal berikut:
Hapus semua file di pub/static/frontend
dan var/view_preprocessed
direktori. Muat ulang halaman.
Langkah 3: Nyatakan formulir dalam tata letak halaman checkout
Untuk menambahkan konten ke langkah Informasi Pengiriman, buat checkout_index_index.xml
pembaruan tata letak di <your_module_dir>/view/frontend/layout/
.
Itu harus mirip dengan yang berikut ini.
<?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>
Bentuk statis:
Contoh kode berikut menunjukkan konfigurasi formulir yang berisi empat bidang: input teks, pilih, kotak centang, dan tanggal. Formulir ini menggunakan penyedia data checkout (checkoutProvider) yang diperkenalkan dalam modul Magento_Checkout:
<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>
Semoga ini membantu.