mg2与mg1同样,checkout页面有country, region, city字段,但只有country和region能实现联动效果,在中国却比较流行国省市三级联动,要应用于中国,三级联动效果必不可少。php
既然只有两级联动,那让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/html
checkout json数据查询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.phpless
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; } }