本文介绍了在 Magento2 中如何用编程的方式创建产品属性。如你所知,Magento2 用 EAV 模块来管理产品,所有不是简单在产品表格中添加一列就能给产品的添加一个属性。本文使用了 Mageplaza HellowWorld 模块为例来添加产品属性。
第一步,新建文件 InstallData.php
从位于 app/code/Mageplaze/HelloWorld/Setup/InstallData.php 的 InstallData 类开始,内容如下:
<?php
namespace Mageplaza\HelloWorld\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
{
private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
}
第二步,定义 install() 方法
<?php
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
}
第三步,创建自定义属性
以下是文件 InstallSchema.php 中创建产品属性的代码:
<?php
namespace Mageplaza\HelloWorld\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
{
private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'sample_attribute',
[
'type' => 'text',
'backend' => '',
'frontend' => '',
'label' => 'Sample Atrribute',
'input' => 'text',
'class' => '',
'source' => '',
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => true,
'required' => true,
'user_defined' => false,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => ''
]
);
}
}
如上所示,addAttribute 方法需要:
-
我们想要添加属性的类型 ID
-
属性的名字
-
用于定义属性的键值对数组比如组别,输入框的类型,标签等
所有准备就绪后,运行这个更新脚本 php bin/magento setup:upgrade 来安装模块和创建产品属性 sample_attribute 。当更新完成后,执行 php bin/magento setup:static-content:deploy 然后去到后台产品表单来检查结果,如下图所示:
如果想要移除产品属性,可以使用 removeAttribute 方法,如下:
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->removeAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'sample_attribute');
}