Skip to content

Instantly share code, notes, and snippets.

Created July 13, 2016 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/66baeeba8ed27c3e4c08e0aef6071e2b to your computer and use it in GitHub Desktop.
Save anonymous/66baeeba8ed27c3e4c08e0aef6071e2b to your computer and use it in GitHub Desktop.
<?php
$array_with_categories = array("BORLETTI", "GROZ-BECKERT", "PFAFF", "SCHMETZ", "SINGER");
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
foreach ($array_with_categories as $row) {
$data = $this->prepareData($row);
$this->createCategory($data);
}
/**
* @param string $row
* @param int $id
* @return array mixed
*/
function prepareData($row, $id = null)
{
// in case you want to user the root category id
//$rootCat = $this->_objectManager->get('Magento\Catalog\Model\Category');
//$cat_info = $rootCat->load($rootrowId);
//$categoryTmp->setPath($rootCat->getPath());
$data = [
'data' => [
"parent_id" => 3,
'name' => (string)$row->Name,
"is_active" => true,
//"position" => 10,
"include_in_menu" => true,
],
'custom_attributes' => [
"display_mode"=> "PRODUCTS",
"is_anchor"=> "1",
/*"custom_use_parent_settings"=> "0",
"custom_apply_to_products"=> "0",
"url_key"=> "", // if not set magento uses the name to generate it
"url_path"=> "cat2",
"automatic_sorting"=> "0",
'my_own_attribute' => 'value' */
]
];
if($id) {
$data['data']['id'] = $id;
}
return $data;
}
/**
* @param array $data
* @return bool
*/
function createCategory(array $data)
{
$category = $this->_objectManager
->create('Magento\Catalog\Model\Category', $data)
->setCustomAttributes($data['custom_attributes']);
$repository = $this->_objectManager->get(CategoryRepositoryInterface::class);
$result = $repository->save($category);
echo "Created Category " . $data['data']['name'] . "\n";
return true;
}
?>
@Laura021
Copy link

Hi Emmanuele,

I also tried to implement ‘as is’ but it goes much more complicated than that.

You need to get a good understanding of Magento architecture.

I first read these articles:
http://alanstorm.com/category/magento-2

The part of the “Object System”

Then create a Command Module using as reference
http://alanstorm.com/magento_2_object_manager

and then try to implement the code above inside the Example model file.

In order to get the code working, inside the Example module file you will need to use:

use \Magento\Catalog\Api\CategoryRepositoryInterface;
use \Magento\Catalog\Api\Data\CategoryInterface;

right before the namespace declaration.

and inside the createCategory funtion you will need 2 objects for the objectManager.

That’s what it took me to get it working.

Hope it helps!
-Laura

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment