3

I currently have the following code which creates a new attribute set:

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

    }

}

However the set has no attributes assigned to it. How would I create the set based on the default one, so it is pre populated with the basic attributes?

Any help much appreciated.

jahilldev
  • 3,520
  • 4
  • 35
  • 52

1 Answers1

2

It turns out the AttributeSetManagementInterface model has a create function that takes an optional skeleton ID which the new set can be based upon. I ended up using objectManager for a quick fix, I'm sure there's a better way.

Below expands on the above OP code:

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

}
jahilldev
  • 3,520
  • 4
  • 35
  • 52