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数据查询
我们将很容易找到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;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。