解決 Magento 2 新增 Product Attribute 自動新增至 Default AttributeSet 問題

當 Magento 使用上有時候需要多個 AttributeSet 來管理多種類的 Product,但是使用內建的 addAttribute 方法帶入 group 參數的時候,會自動新增至每一個 AttributeSet, 可是偏偏不是每一個 AttributeSet 都需要此屬性。我們今天就來看看到底是怎麼回事!
1. 新增 Attribute
通常會寫在 InstallData.php 內,今天我們就不特別說明新增的部分但是在新增的時候,我們首先要把 group 選項移除掉,並且加上 user_defined 選項,並給予 true 值。
$eavSetup->addAttribute( \Magento\Catalog\Model\Product::ENTITY, 'datetime_example', [ 'label' => 'datetime example' 'group'=> 'example_group' ---這項移除 'user_defined'=> true, ---這項要新增 'type' => 'datetime', 'input' => 'date', 'backend' => Startdate::class, 'required' => false, 'global' => ScopedAttributeInterface::SCOPE_GLOBAL, 'visible' => true, 'searchable' => false, 'filterable' => false, 'filterable_in_search' => false, 'visible_in_advanced_search' => false, 'comparable' => false, 'visible_on_front' => false, 'used_in_product_listing' => false, 'unique' => false ] );
2. 原始碼追蹤
大家一定會很好奇為什麼會這樣自動新增至 Default AttributeSet,原來是因為官方有段程式碼這樣寫:
> vendor/magento/module-eav/Setup/EavSetup.php:826
裡面有一個 foreach,會自動新增至所有的 AttributeSet,所以不要官方幫我們新增的話,記得要把 group 選項拿掉即可。
if (!empty($attr['group']) || empty($attr['user_defined'])) {
           $select = $this->setup->getConnection()->select()->from(
               $this->setup->getTable('eav_attribute_set')
           )->where(
               'entity_type_id = :entity_type_id'
           );
           $sets = $this->setup->getConnection()->fetchAll($select, ['entity_type_id' => $entityTypeId]);
           foreach ($sets as $set) {
               if (!empty($attr['group'])) {
                   $this->addAttributeGroup($entityTypeId, $set['attribute_set_id'], $attr['group']);
                   $this->addAttributeToSet(
                       $entityTypeId,
                       $set['attribute_set_id'],
                       $attr['group'],
                       $code,
                       $sortOrder
                   );
               } else {
                   $this->addAttributeToSet(
                       $entityTypeId,
                       $set['attribute_set_id'],
                       $this->_generalGroupName,
                       $code,
                       $sortOrder
                   );
               }
           }
       }
適用版本:
- Magento 2.0 以上
簡單的程式編寫,就可以有不一樣的功能,我們歐斯瑞會不定期提供Magento簡易的相關教學文章,有興趣的也可以關注我們Facebook的粉絲專頁喔!
 
	 
			 
			 
			 
			 
			 
			
我要留言