首页 > 解决方案 > 如何在地址编辑 Magento 2 上显示/保存自定义客户地址属性的值

问题描述

我想在 customer_address 上添加自定义属性。我需要将值保存在数据库中,在前端表单(新/编辑地址)和后端触发值。

我使用以下 InstallData 脚本来添加新属性:

$installer = $setup;
$installer->startSetup();

/* @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->removeAttribute('customer_address', "chamber_of_commerce");

$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer_address'); //customer
$attributeSetId = $customerEntity->getDefaultAttributeSetId();

$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

$customerSetup->addAttribute('customer_address', 'chamber_of_commerce', [
    'type' => 'varchar',
    'label' => 'Chamber of Commerce',
    'input' => 'text',
    'required' => false,
    'visible' => true,
    'user_defined' => true,
    'system' => false,
    'sort_order' => 150
]);

$attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'chamber_of_commerce')
    ->addData([
        'attribute_set_id' => $attributeSetId,
        'attribute_group_id' => $attributeGroupId,
        'used_in_forms'=>['adminhtml_customer_address','customer_address_edit','customer_register_address']
    ]);

$attribute->save();

$installer->endSetup(); 

我使用'used_in_forms'=>['adminhtml_customer_address','customer_address_edit','customer_register_address'] 了`,但似乎只在后端表单中自动添加并且还保存了一个新值。

我手动添加了一个输入,以便在 CustomerAccount 中的新/编辑地址的前端显示属性,但我无法从数据库中获取值或保存新值。

我想我错过了一些东西,如果有人可以看一下并给出提示,我将非常感激。

我正在使用 Magento 2.2.4

更新: 1. 我使用了 Magento\Customer\Model\Address 的观察者,以便从 MyAccount 页面保存编辑/新地址的值。

  1. 为了从结帐页面中获取保存的值,我使用了:

2.1。客户地址接口的 extension_attributes

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

2.2. 等/字段集:

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

2.3. 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>

标签: magento2addressbookcustomercustom-attribute

解决方案


推荐阅读