我正在写一个magento 2模块-我试图让它为每个产品添加一个自定义属性。我的“Setup〉InstallData.php”文件在安装模块时成功地将属性添加到“eav_attribute”表中,而adminhtml将字段呈现为具有“name=product[my_attribute]",我认为这意味着它“接受”该字段作为模型的有效部分。然而,当尝试使用自定义属性中的值保存产品时,数据库中不会保存任何内容。
下面是我代码:
<?php
// module namespace is 'Duel', module name is 'Gallery'
namespace Duel\Gallery\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->_eavSetupFactory = $eavSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/**@var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
/**
* Add attributes to the eav/attribute
*/
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'my_attribute',
[
'type' => 'text',
'backend' => '',
'label' => 'My New Attribute',
'input' => 'text',
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
'visible' => true,
'user_defined' => true,
'required' => false,
'visible_on_front' => true
]
);
}
}
下面是视图中的html〉管理html〉用户界面组件〉产品表单.xml
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="attributes">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">MY CUSTOM ATTRIBUTE</item>
<item name="collapsible" xsi:type="boolean">true</item>
<item name="sortOrder" xsi:type="number">200</item>
</item>
</argument>
<field name="my_attribute">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">My new attribute</item>
<item name="formElement" xsi:type="string">textarea</item>
</item>
</argument>
</field>
</fieldset>
在手动更改了'eav_attribute'表中的'my_attribute'的几个字段后,我短暂地保存了它,但是我提交了代码,但愚蠢地没有保存确切的mysql数据库状态,现在无法让它再次工作(在测试中,每次安装模块时,它都会创建一个工作表单)。
非常感谢您的帮助!
2条答案
按热度按时间unftdfkk1#
因为你应该把数组中的键从user_defined改为**is_**user_defined,这样一切就都好了,可以保存它......
pbgvytdp2#
user_defined = true(仅创建属性,不为任何属性集分配属性)