
– один із найважливіших кроків, які роблять ваші клієнти на своєму шляху. Тому в інтересах кожного власника магазину зробити його максимально безпроблемним.
Тим не менш, полів оформлення замовлення за замовчуванням у Magento 2 не завжди достатньо для потреб вашого магазину. Вам може знадобитися зібрати додаткову інформацію про клієнтів, щоб покращити свій сервіс. У цьому випадку вам слід знати, як додати користувацькі поля в оформленні замовлення Magento 2.
Якщо ви ще не зрозуміли, як це зробити, саме це ви дізнаєтесь сьогодні.
За замовчуванням Magento 2 не надає можливості додавати користувацькі поля оформлення замовлення через панель адміністратора. Ось чому вам потрібно буде зробити це програмно, виконавши наведені нижче кроки. Отже, давайте одразу перейдемо до них.
1. Створіть новий модуль
Для початку визначтеся, яке поле ви хочете додати. Наприклад, ви можете вибрати поле "delivery_date" . Наступний крок - створити Basic модуль у Magento , використовуючи наступний метод.
Створіть файл Magefan/DeliveryDate/registration.php та додайте наступний вміст:
<?php
use \Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE,
'Magefan_Deliverydate', __DIR__);
Аналогічно, додайте наведений нижче код до файлу Magefan/DeliveryDate/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="Magefan_DeliveryDate" setup_version="1.0.0">
<sequence>
<module name="Magento_Sales"/>
</sequence>
</module>
</config>
2. Оновіть деякі таблиці
Тепер вам потрібно додати стовпець "delivery_date" до таких таблиць, як "sales_order", "sales_order_grid" та "quote". Оскільки клієнти вводитимуть дату, тип поля має бути DateTime.
Якщо ви хочете додати інший тип поля та зберегти його вміст як рядок, ви можете налаштувати наступний код відповідно до ваших потреб.
<?php
namespace Magefan\DeliveryDate\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class InstallSchema implements InstallSchemaInterface
{
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();
}
}
3. Додайте користувацьке поле на сторінку оформлення замовлення
Після виконання попередніх кроків ви готові додати поле на сторінку оформлення замовлення. Тут вам потрібно буде попрацювати з фронтендом. Точніше, вам потрібно створити файл Magefan/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="Magefan\DeliveryDate\Plugin\Checkout\LayoutProcessorPlugin"
sortOrder="10"/>
</type>
</config>
Потім додайте наступний вміст до файлу Magefan/DeliveryDate/Plugin/Checkout/LayoutProcessorPlugin.php :
<?php
namespace Magefan\DeliveryDate\Plugin\Checkout;
class LayoutProcessorPlugin
{
/**
* @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/date',
'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'
];
return $jsLayout;
}
}
На цьому етапі ви вже зможете побачити користувацьке поле на вітрині магазину.
![]()
4. Зберіть дані, додані до нового поля
Поряд з цим, вам також потрібно зберегти дані, які вводять ваші клієнти, щоб ви могли відповідно обробка замовлень . Усі сторінки оформлення замовлення Magento 2 створені за допомогою knockout JS та API. Отже, спочатку вам потрібно додати деякі .js файли до Magefan/DeliveryDate/view/frontend/requirejs-config.js:
var config = {
config: {
mixins: {
'Magento_Checkout/js/action/place-order': {
'Magefan_DeliveryDate/js/order/place-order-mixin': true
},
}
}
};
. Тепер, використовуючи Ajax, додайте значення вашого поля до Magefan/DeliveryDate/view/frontend/web/js/order/place-order-mixin.js:
define([
'jquery',
'mage/utils/wrapper',
'Magento_CheckoutAgreements/js/model/agreements-assigner',
'Magento_Checkout/js/model/quote',
'Magento_Customer/js/model/customer',
'Magento_Checkout/js/model/url-builder',
'mage/url',
'Magento_Checkout/js/model/error-processor',
'uiRegistry'
], function (
$,
wrapper,
agreementsAssigner,
quote,
customer,
urlBuilder,
urlFormatter,
errorProcessor,
registry
) {
'use strict';
return function (placeOrderAction) {
/** Override default place order action and add agreement_ids to request */
return wrapper.wrap(placeOrderAction, function (originalAction, paymentData, messageContainer) {
agreementsAssigner(paymentData);
var isCustomer = customer.isLoggedIn();
var quoteId = quote.getQuoteId();
var url = urlFormatter.build('mfcustom/quote/save');
var deliveryDate = $('[name="delivery_date"]').val();
if (deliveryDate) {
var payload = {
'cartId': quoteId,
'delivery_date': deliveryDate,
'is_customer': isCustomer
};
if (!payload.delivery_date) {
return true;
}
var result = true;
$.ajax({
url: url,
data: payload,
dataType: 'text',
type: 'POST',
}).done(
function (response) {
result = true;
}
).fail(
function (response) {
result = false;
errorProcessor.process(response);
}
);
}
return originalAction(paymentData, messageContainer);
});
};
});
. Наступним кроком є створення Magefan/DeliveryDate/Controller/Quote/Save.php :
<?php
namespace Magezon\Deliverydate\Controller\Quote;
class Save extends \Magento\Framework\App\Action\Action
{
protected $quoteIdMaskFactory;
protected $quoteRepository;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Quote\Model\QuoteIdMaskFactory $quoteIdMaskFactory,
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository
) {
parent::__construct($context);
$this->quoteRepository = $quoteRepository;
$this->quoteIdMaskFactory = $quoteIdMaskFactory;
}
/**
* @return \Magento\Framework\Controller\Result\Raw
*/
public function execute()
{
$post = $this->getRequest()->getPostValue();
if ($post) {
$cartId = $post['cartId'];
$deliveryDate = $post['delivery_date'];
$loggin = $post['is_customer'];
if ($loggin === 'false') {
$cartId = $this->quoteIdMaskFactory->create()->load($cartId, 'masked_id')->getQuoteId();
}
$quote = $this->quoteRepository->getActive($cartId);
if (!$quote->getItemsCount()) {
throw new NoSuchEntityException(__('Cart %1 doesn\'t contain products', $cartId));
}
$quote->setData('delivery_date', $deliveryDate);
$this->quoteRepository->save($quote);
}
}
}
. Вам також потрібно ввімкнути Ajax для надсилання зібраних даних до контролера. Ви можете зробити це так:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="mgzcustom" frontName="mgzcustom">
<module name="Magezon_Deliverydate" />
</route>
</router>
</config>
Нарешті, ви можете завершити цей крок, створивши Magefan/DeliveryDate/etc/events.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_model_service_quote_submit_before">
<observer name="save_delivery_date_to_order"
instance="Magefan\DeliveryDate\Observer\SaveToOrder" />
</event>
</config>
5. Відобразіть нове значення в сітці замовлення на продаж
І останнє, але не менш важливе: вам також потрібно відобразити створене значення в сітці замовлення на продаж. Вам потрібно створити файл sales_order_grid.xml та додати стовпець «Дата доставки» до Magefan/DeliveryDate/view/adminhtml/ui_component/sales_order_grid.xml:
<?xml version="1.0"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<columns name="sales_order_columns">
<column name="delivery_date" class="Magefan\DeliveryDate\Ui\Component\Listing\Column\DeliveryDate">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="visible" xsi:type="boolean">true</item>
<item name="label" xsi:type="string" translate="true">Delivery Date</item>
<item name="dateFormat" xsi:type="string">Y-MM-dd</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
<item name="dataType" xsi:type="string">date</item>
</item>
</argument>
</column>
</columns>
</listing>
Щоб дані відображалися в цьому стовпці, вам потрібно внести такі зміни в Magefan/DeliveryDate/Ui/Component/Listing/Column/DeliveryDate.php:
<?php
namespace Magefan\DeliveryDate\Ui\Component\Listing\Column;
use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Framework\View\Element\UiComponent\ContextInterface;
use \Magento\Framework\View\Element\UiComponentFactory;
use \Magento\Ui\Component\Listing\Columns\Column;
use \Magento\Framework\Api\SearchCriteriaBuilder;
class DeliveryDate extends Column
{
protected $_orderRepository;
protected $_searchCriteria;
public function __construct(ContextInterface $context, UiComponentFactory
$uiComponentFactory, OrderRepositoryInterface $orderRepository,
SearchCriteriaBuilder $criteria, array $components = [], array $data = [])
{
$this->_orderRepository = $orderRepository;
$this->_searchCriteria = $criteria;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
$order = $this->_orderRepository->get($item["entity_id"]);
$date = $order->getData("delivery_date");
$item[$this->getData('name')] = $date;
}
}
return $dataSource;
}
}
Після виконання цих кроків ви отримаєте наступний результат.
![]()
Отже, вам вдалося додати користувацьке поле до оформлення замовлення Magento 2?
Створення користувацьких полів оформлення замовлення в Magento 2 — це завдання, з яким не можна швидко впоратися. Воно має багато етапів, що робить весь процес дещо складним. Тим не менш, кінцевий результат вартий ваших зусиль. Чим більше інформації про клієнтів ви зможете зібрати, тим кращий сервіс ви запропонуєте.
Однак не забувайте про саму сторінку оформлення замовлення. Вам потрібно зробити її максимально зручною для користувача. Тому ви також можете додайте значки способів оплати до оформлення замовлення або встановити спосіб оплати за замовчуванням .