Magento 2.2. Пользовательский атрибут Клиента
Я хочу добавить бонус своему клиенту, в Интернете я прочитал, что мне нужно использовать пользовательский атрибут.
Etc/Module.xml
<module name="Kt_Addbonus" setup_version="1.2.2">
<sequence>
<module name="Customer"/>
</sequence>
</module>
Setup/InstallData.php
<?php
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
class InstallData implements InstallDataInterface
{
/**
* @var CustomerSetupFactory
*/
private $customerSetupFactory;
/**
* @var AttributeSetFactory
*/
private $attributeSetFactory;
public function __construct( CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory)
{
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
/**
* Installs data for a module
*
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
* @return void
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$setup->startSetup();
$attributesInfo = [
'customer_bonus' => [
'label' => 'Customer Bonus',
'type' => 'int',
'input' => 'text',
'position' => 1000,
'visible' => true,
'required' => false,
'system' => 0,
'user_defined' => true,
]
];
$customerEntity =$customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultGroupId();
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
foreach ($attributesInfo as $attributeCode => $attributeParams) {
$customerSetup->addAttribute(Customer::ENTITY, $attributeCode, $attributeParams);
}
$customerBonusAttribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'customer_bonus');
$customerBonusAttribute->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms'=>['adminhtml_customer']
]);
$customerBonusAttribute->save();
$setup->endSetup();
}
}
Пользовательский атрибут не добавляется в базу данных или на страницу администратора "Создать клиента". И PhpStorm говорит мне, что CustomerSetupFactory не найден, я уже пробовал
setup:di:compile
setup:upgrade and cache:flush
Тоже сделал.
Обновление 1
Был создан Customersetupfactory. Но пользовательский атрибут все еще не добавлен.
4 answers
Пожалуйста, подтвердите, что вы создали registration.php в корневой папке вашего модуля, например:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE, 'Kt_Addbonus', __DIR__
);
Также замените следующий код в свой InstallData.php
<?php
namespace Kt\Addbonus\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $customerSetupFactory;
private $attributeSetFactory;
public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory, \Magento\Eav\Model\Entity\Attribute\SetFactory $attributeSetFactory)
{
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
/** @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->removeAttribute(\Magento\Customer\Model\Customer::ENTITY, "customer_bonus");
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'customer_bonus', [
'type' => 'varchar',
'label' => 'Customer Bonus',
'input' => 'text',
'required' => false,
'visible' => true,
'user_defined' => true,
'system' => false,
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'customer_bonus')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms'=>['adminhtml_customer']
]);
$attribute->save();
$installer->endSetup();
}
}
После того, как выше вы должны снова запустить свое расширение, вам нужно удалить запись о своем расширении из таблицы setup_module, а затем выполнить команду ниже
php bin/magento setup:upgrade
Спасибо
Я думаю, что вам не хватает namespace
в вашем сценарии установки,
<?php
namespace Kt\Addbonus\Setup;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* @var CustomerSetupFactory
*/
protected $customerSetupFactory;
/**
* @var AttributeSetFactory
*/
private $attributeSetFactory;
/**
* @param CustomerSetupFactory $customerSetupFactory
* @param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
/** @var $attributeSet AttributeSet */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(Customer::ENTITY, 'custom_attribute', [
'type' => 'varchar',
'label' => 'Customer Bonus',
'input' => 'text',
'required' => false,
'visible' => true,
'user_defined' => true,
'position' =>999,
'system' => 0,
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'custom_attribute')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer'],//you can use other forms also ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']
]);
$attribute->save();
}
}
Вы не можете легко использовать пользовательские атрибуты клиентов в Magento 2 community edition. Это платная функция в Enterprise Edition.
Вы можете добавить его программно, но, на мой взгляд, они многое сделали, чтобы сделать его как можно более сложным.
Смотрите эту тему для справки: https://github.com/magento/magento2/issues/6575
Я создал модуль, который позволяет добавлять атрибут клиента/адреса из серверной части здесь
Может быть, кому-то еще это понадобится.