Last active
June 19, 2024 17:20
-
-
Save 0-Sony/17a44ec037ca98926d25f0814294dc23 to your computer and use it in GitHub Desktop.
Magento2: Create Category By Setup Install
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace Namespace\Category\Setup; | |
| use Magento\Catalog\Api\CategoryRepositoryInterface; | |
| use Magento\Catalog\Api\Data\CategoryInterface; | |
| use Magento\Catalog\Api\Data\CategoryInterfaceFactory; | |
| use Magento\Framework\Setup\InstallDataInterface; | |
| use Magento\Framework\Setup\ModuleContextInterface; | |
| use Magento\Framework\Setup\ModuleDataSetupInterface; | |
| class InstallData implements InstallDataInterface | |
| { | |
| /** @var CategoryRepositoryInterface */ | |
| private $categoryRepositoryInterface; | |
| /** @var CategoryInterfaceFactory */ | |
| private $categoryInterfaceFactory; | |
| public function __construct( | |
| CategoryRepositoryInterface $categoryRepository, | |
| CategoryInterfaceFactory $categoryInterfaceFactory | |
| ) { | |
| $this->categoryRepositoryInterface = $categoryRepository; | |
| $this->categoryInterfaceFactory = $categoryInterfaceFactory; | |
| } | |
| /** | |
| * Installs data for a module | |
| * | |
| * @param ModuleDataSetupInterface $setup | |
| * @param ModuleContextInterface $context | |
| * @return void | |
| */ | |
| public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) | |
| { | |
| $this->createCategory(); | |
| } | |
| public function createCategory() | |
| { | |
| $categoriesName = array('Gaz', 'Fioul'); | |
| foreach ($categoriesName as $categoryName){ | |
| /** new category instance **/ | |
| $category = $this->categoryInterfaceFactory->create(); | |
| $category->setName($categoryName); | |
| /** set root category as parent category **/ | |
| $category->setParentId(2); | |
| $category->setIsActive(1); | |
| $category->setData('stores', [0]); | |
| $this->categoryRepositoryInterface->save($category); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment