
この記事では、Magento 2 で製品の属性をプログラムで作成する方法を説明します。ご存知のように、Magento 2 は EAV モデルで Product を管理しているので、Product テーブルにカラムを追加して Product の属性を単純に追加することはできません。この点については、Magento 2 EAV モデルの記事をお読みください。
その前に、Magento 2 Install/Upgrade script という記事を読んで、モジュールセットアップクラスの作り方を知っておいてください。
ステップ1:InstallData.phpファイルの作成
まずは、app/code/Mageplaza/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;
}
}
ステップ2: installメソッドの定義
<?php
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
}
ステップ3:カスタム属性の作成
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を実行し、管理画面から商品にアクセスして結果を確認してください。

製品の属性を削除したい場合は、addAttributeの代わりにremoveAttributeというメソッドを使用します。これは次のようになります:
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->removeAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'sample_attribute');
}