Magento2 не сохраняет пользовательский атрибут для клиента

#php #magento #entity-attribute-value

#php #magento #сущность-атрибут-значение

Вопрос:

Я добавил новое поле в серверную часть Magento 2 для клиента, которое видно. Я создал это с помощью mage2gen, но что бы я ни пытался, новое поле не сохраняется при обновлении его в серверной части.

Поскольку поле видно в серверной части, и как представление, так и api работают должным образом, я понятия не имею, почему оно не работает. Ниже фактического исправления я добавляю поле и конфигурацию xml, чтобы сделать его также видимым.

Я попытался добавить его в attributeset, но, насколько я вижу, поле зарегистрировано правильно и также присутствует в customer_eav_attribute

 <?xml version="1.0" ?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <fieldset name="general">
        <field formElement="text" name="external_reference" sortOrder="20">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">external_reference</item>
                </item>
            </argument>
            <settings>
                <dataType>text</dataType>
                <label translate="true">External reference</label>
                <dataScope>external_reference</dataScope>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">false</rule>
                </validation>
            </settings>
        </field>
    </fieldset>
</form>
 
 <?php

declare(strict_types=1);

namespace MeDirectLoginSetupPatchData;

use MagentoCustomerApiCustomerMetadataInterface;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupPatchDataPatchInterface;
use MagentoFrameworkSetupPatchPatchRevertableInterface;

class AddExternalReferenceCustomerAttribute implements DataPatchInterface, PatchRevertableInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;
    /**
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Constructor
     *
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        EavSetupFactory $eavSetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $this->moduleDataSetup->getConnection()->startSetup();
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
        $eavSetup->addAttribute(
            MagentoCustomerModelCustomer::ENTITY,
            'external_reference',
            [
                'type' => 'varchar',
                'label' => 'External reference',
                'input' => 'text',
                'source' => '',
                'frontend' => '',
                'required' => false,
                'backend' => '',
                'default' => null,
                'user_defined' => true,
                'unique' => true,
                'group' => 'General',
                'system' => 0,
                'order' => 1000,
                'note' => 'Reference to external managed user',
                'is_used_in_grid' => false,
                'is_visible_in_grid' => true,
                'is_filterable_in_grid' => true,
                'is_searchable_in_grid' => true,
            ]
        );

        $eavSetup->addAttributeToSet(
            CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
            CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
            null,
            'external_reference'
        );

        $this->moduleDataSetup->getConnection()->endSetup();
    }

    public function revert()
    {
        $this->moduleDataSetup->getConnection()->startSetup();
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
        $eavSetup->removeAttribute(MagentoCustomerModelCustomer::ENTITY, 'external_reference');

        $this->moduleDataSetup->getConnection()->endSetup();
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [

        ];
    }
}

 

Надеюсь, кто-нибудь может указать мне на решение

Лучший, Pim

Ответ №1:

Я проверил, что ваш код немного отличается от фактического кода mage2gen. Например, вы не добавили данные для «used_in_forms». Вы можете попробовать приведенный ниже код для создания пользовательского атрибута клиента (если вы хотите использовать mage2gen)
https://mage2gen.com/snippets/customerattribute/

Или же вы можете попробовать использовать метод установки. Проверьте ниже URL блога Mageplaza:
https://www.mageplaza.com/magento-2-module-development/magento-2-add-customer-attribute-programmatically.html

Комментарии:

1. Это работает так хорошо, НЕТ! Ошибка типа: аргумент 2, переданный в MagentoFrameworkViewElementUiComponentFactory::argumentsResolver(), должен иметь тип array, заданный null, вызываемый в /app/vendor/magento/framework/View/Element/UiComponentFactory.php в строке 235 и определен в

2. Пожалуйста, запустите команду компиляции, а затем проверьте.

Ответ №2:

Попробуйте использовать следующее в Setup / Patch / Data path

 <?php

namespace VendorCustomerSetupPatchData;

use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;
use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupPatchDataPatchInterface;

class AddCustomerRefId implements DataPatchInterface
{
    const EXTERNAL_REFERENCE = "external_reference";

    /**
     * @var ModuleDataSetupInterface
     */
    protected $moduleDataSetup;

    /**
     * @var CustomerSetupFactory
     */
    protected $customerSetupFactory;

    /**
     * @var AttributeSetFactory
     */
    protected $attributeSetFactory;

    /**
     * AddCustomerPhoneNumberAttribute constructor.
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param CustomerSetupFactory $customerSetupFactory
     * @param AttributeSetFactory $attributeSetFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $customerSetup->removeAttribute(
            Customer::ENTITY,
            self::EXTERNAL_REFERENCE
        );

        $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

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

        $customerSetup->addAttribute(
            Customer::ENTITY,
            self::EXTERNAL_REFERENCE,
            [
                'type' => 'varchar',
                'label' => 'External Reference',
                'required' => false,
                'user_defined' => true,
                'sort_order' => 1000,
                'position' => 1000,
                'default' => 0,
                'system' => 0
            ]
        );

        $attribute = $customerSetup->getEavConfig()->getAttribute(
            Customer::ENTITY,
            self::EXTERNAL_REFERENCE
        );

        $attribute->addData(
            [
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['adminhtml_customer','customer_account_create','customer_account_edit']
            ]
        );

        $attribute->save();
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
}