Magento 2 - 如何根据默认值创建属性集

时间:2016-01-15 11:59:26

标签: php magento2 magento-2.0

我目前有以下代码创建一个新的属性集:

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);

    }

}

但是该集合没有分配属性。如何根据默认值创建集合,因此预先填充了基本属性?

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:2)

事实证明,AttributeSetManagementInterface模型有一个create函数,它接受新集合可以基于的可选框架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();

}