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; } }