2016-01-15 32 views
3

創建一個屬性集目前,我有以下代碼創建一個新的屬性設置:Magento的2 - 如何基於默認

use Magento\Framework\ObjectManagerInterface; 
use Magento\Eav\Setup\EavSetupFactory; 
use Magento\Framework\Setup\ModuleDataSetupInterface; 

class AttributeModel extends \Magento\Framework\Model\AbstractModel 
{ 

    const ENTITY_TYPE = \Magento\Catalog\Model\Product::ENTITY; 

    protected $_objectManager; 
    protected $_moduleDataSetup; 
    protected $_eavSetupFactory; 

    public function __construct(
     ObjectManagerInterface $objectManager, 
     ModuleDataSetupInterface $moduleDataSetup, 
     EavSetupFactory $eavSetupFactory, 
    ) { 

     $this->_objectManager = $objectManager; 
     $this->_moduleDataSetup = $moduleDataSetup; 
     $this->_eavSetupFactory = $eavSetupFactory; 

    } 

    public function createSet($name) 
    { 

     $eavSetup = $this->_eavSetupFactory->create([ 
      'setup' => $this->_moduleDataSetup 
     ]); 

     $eavSetup->addAttributeSet(self::ENTITY_TYPE, $name, 0); 

    } 

} 

但是set沒有分配給它的屬性。我將如何創建基於默認設置的集合,因此它預先填充了基本屬性?

任何幫助非常感謝。

回答

2

事實證明,AttributeSetManagementInterface模型有一個創建函數,該函數採用新集可以基於的可選骨架ID。我最終使用objectManager進行了快速修復,我確信有更好的方法。

下面擴展了上述OP代碼:

public function createSet($name) 
{ 

    $eavSetup = $this->_eavSetupFactory->create([ 
     'setup' => $this->_moduleDataSetup 
    ]); 

    $defaultId = $eavSetup->getDefaultAttributeSetId(self::ENTITY_TYPE); 

    $model = $this->_objectManager 
    ->create('Magento\Eav\Api\Data\AttributeSetInterface') 
    ->setId(null) 
    ->setEntityTypeId(4) 
    ->setAttributeSetName($name); 

    $this->_objectManager 
    ->create('Magento\Eav\Api\AttributeSetManagementInterface') 
    ->create(self::ENTITY_TYPE, $model, $defaultId) 
    ->save(); 

}