magento2 checkout页面实现国省市三级联动

mg2与mg1一样,checkout页面有country, region, city字段,但只有country和region能实现联动效果,在中国却比较流行国省市三级联动,要应用于中国,三级联动效果必不可少。

既然只有两级联动,那让city也联动起来就可以了。但mg2与mg1架构上有极大的差别,mg2大量使用到UI Component,PHP只需提供数据,大量的呈现效果由js, less, html来实现。而checkout是个庞大而且多重层叠的UI Component,要改造它前需要先看到它的LAYOUT结构。在LAYOUT数据提供给UI Component之前,PHP已经把XML格式的LAYOUT数据转换为JSON,并且在页面代码中就能找到。但庞大的LAYOUT JSON数据阅读起来相当困难,我们需要更好的JSON阅读工具。
http://braincast.nl/samples/jsoneditor/

checkout json数据查询
checkout json数据查询

我们将很容易找到city的ui配置,很明显它使用的是text,把它改为select就可以。使用plugin可以对layout进行深度加工,具体实现方法如下:
di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Block\Checkout\LayoutProcessor">
        <plugin name="checkout_city" type="Vendor\Module\Plugin\Checkout\LayoutProcessor" />
    </type>
</config>

LayoutProcessor.php

namespace Vendor\Module\Plugin\Checkout;

class LayoutProcessor
{
    public function afterProcess( \Magento\Checkout\Block\Checkout\LayoutProcessor $subject, $jsLayout )
    {
        $city = $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['city'];

        $city['component'] = 'Magento_Ui/js/form/element/select';
        $city['config']['elementTmpl'] = 'ui/form/element/select';
        unset($city['validation']);
        $city['value'] = '';
        // city关联数据
        $city['options'] = [
            ['value' => '', 'label' => '请选择'],
            ['value' => 'city 1', 'label' => 'city 1', 'region_id' => '514'],
            ['value' => 'city 2', 'label' => 'city 2', 'region_id' => '514']
        ];
        $city['filterBy'] = [
            'target' => '${ $.provider }:${ $.parentScope }.region_id',
            'field' => 'region_id'
        ];
        $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['city'] = $city;
        return $jsLayout;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值