系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》
本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。
以下是您需要遵循并在Magento 2商店中应用的步骤和代码,以将自定义验证添加到结帐中的地址字段。
在给定路径处创建一个文件,
app\code\Vendor\Extension\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="custom-validation-street-address" type="Vendor\Extension\Model\Checkout\Layoutprocessorplugin"/> </type> </config>
如果您的商店支持多供应商功能,请为每个供应商执行上述步骤。
在给定路径处创建另一个文件,
app\code\Vendor\Extension\Model\Checkout\Layoutprocessorplugin.php
创建文件后,使用以下代码应用自定义验证,
<?php namespace Vendor\Extension\Model\Checkout; class Layoutprocessorplugin { public function afterProcess( \Magento\Checkout\Block\Checkout\LayoutProcessor $subject, array $jsLayout ) { $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children'] ['billingAddress']['children']['shipping-address-fieldset']['children']['street'] = [ 'component' => 'Magento_Ui/js/form/components/group', 'label' => __('Street Address'), 'required' => true, 'dataScope' => 'billingAddress.street', 'provider' => 'checkoutProvider', 'sortOrder' => 10, 'type' => 'group', 'additionalClasses' => 'street', 'children' => [ [ 'component' => 'Magento_Ui/js/form/element/abstract', 'config' => [ 'customScope' => 'billingAddress', 'template' => 'ui/form/field', 'elementTmpl' => 'ui/form/element/input' ], 'dataScope' => '0', 'provider' => 'checkoutProvider', 'validation' => ['required-entry validate-alphanum-with-spaces' => true, "min_text_length" => 5, "max_text_length" => 255], ], [ 'component' => 'Magento_Ui/js/form/element/abstract', 'config' => [ 'customScope' => 'shippingAddress', 'template' => 'ui/form/field', 'elementTmpl' => 'ui/form/element/input' ], 'dataScope' => '1', 'provider' => 'checkoutProvider', 'validation' => ['required-entry validate-alphanum-with-spaces' => true, "min_text_length" => 5, "max_text_length" => 255], ] ] ]; return $jsLayout; } }
应用代码后,清除缓存并刷新它。自定义验证现在将开始工作。所以今天,我们了解到如何在Magento 2平台结帐时将自定义验证添加到地址字段。使用此处描述的代码,您将能够在结帐中设置自定义验证地址字段。此外,安装自定义结帐字段,这有助于商店管理员通过添加额外字段来自定义结帐页面。