如何在结帐时保存新的地址属性

How to save a new address attribute in checkout

我正在尝试将地理位置与客户地址一起保存。

我已经使用安装脚本添加了 Let 和 Lng

    $customerSetup->addAttribute('customer_address', 'latitude', [
        'type' => 'varchar',
        'label' => 'Latitude',
        'input' => 'text',
        'required' => false,
        'visible' => true,
        'visible_on_front' => true,
        'user_defined' => false,
        'sort_order' => 43,
        'position' => 43,
        'system' => 0,
    ]);

    $attributeLat = $customerSetup->getEavConfig()->getAttribute('customer_address', 'latitude')
        ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address','customer_address'],
        ]);
    $attributeLat->save();
    //latitude - End

    $customerSetup->addAttribute('customer_address', 'longitude', [
        'type' => 'varchar',
        'label' => 'Longitude',
        'input' => 'text',
        'required' => false,
        'visible' => true,
        'visible_on_front' => true,
        'user_defined' => false,
        'sort_order' => 43,
        'position' => 43,
        'system' => 0,
    ]);

    $attributeLng = $customerSetup->getEavConfig()->getAttribute('customer_address', 'longitude')
        ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address','customer_address'],
        ]);
    $attributeLng->save();
    //longitude - End}

我可以毫无问题地在管理后端更新值。

在结帐页面的表单字段中出现了“纬度”和“经度”。但值不会与客户地址一起保存。

我正在使用 Magento CE 2.2.3

您需要为 Magento\Customer\Api\Data\AddressInterface 添加 etc/extension_attributes.xml:

<extension_attributes for="Magento\Customer\Api\Data\AddressInterface">
        <attribute code="longitude" type="string" />
    </extension_attributes>

添加etc/fieldset.xml:

 <fieldset id="sales_convert_quote_address">
            <field name="longitude">
                <aspect name="to_customer_address" />
                <aspect name="to_order_address" />
            </field>
        </fieldset>

在 di.xml 中为 Magento\Customer\Model\Address 添加插件,您需要在 beforeUpdateData 函数中保存自定义属性

<type name="Magento\Customer\Model\Address"> 
        <plugin disabled="false" name="vendor_plugin_quote_model_address" sortOrder="10" 
        type="Vendor\Module\Plugin\Customer\Model\Address"/>
    </type>
  public function beforeUpdateData(
        \Magento\Customer\Model\Address $subject,
        \Magento\Customer\Api\Data\AddressInterface $address
    )

然后您应该能够看到您的属性保存在客户地址上。