DanielDake
DanielDake

Reputation: 25

How to create subcategories in Magento using API SOAP?

I am using Magento standard API SOAP to create categories and sub-categories.

Here is the code i am using to insert categories:

$client = new SoapClient('http://magentohost/api/soap/?wsdl');

$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'catalog_category.create', array(2, array(
'name' => 'Category name',
'is_active' => 1,
'position' => 1,

'available_sort_by' => 'position',
'custom_design' => null,
'custom_apply_to_products' => null,
'custom_design_from' => null,
'custom_design_to' => null,
'custom_layout_update' => null,
'default_sort_by' => 'position',
'description' => 'Category description',
'display_mode' => null,
'is_anchor' => 0,
'landing_page' => null,
'meta_description' => 'Category meta description',
'meta_keywords' => 'Category meta keywords',
'meta_title' => 'Category meta title',
'page_layout' => 'two_columns_left',
'url_key' => 'url-key',
'include_in_menu' => 1,
)));

Til here everything is ok, and success, But i am really confuse how to put subcategories under the categories i have created. I have tried using catalog_category.move but no result.

Any of you been through this trick? Thank you

Upvotes: 0

Views: 1321

Answers (2)

Dhananjay Hegde
Dhananjay Hegde

Reputation: 1

I know this is a 2 year old thread. But I am still posting my answer. It might help someone.

I am new to Magento and this is my first project. So, not sure if below code is really very efficient. I used SOAP catalog_category.create :

<?php
/**
 *                      ---NOTE---NOTE---NOTE---
 * Upload file must contain only those fields where the value is neither null nor blank.
 * Default values are already set for all the fields.
 * @var unknown
 */

$target_dir = "uploads/";
$filename = "category_tree_create_1443881125.csv";
$target_file = $target_dir . $filename;

//Web service sessoin initialization
$proxy = new SoapClient('http://localhost/magento-dhana/api/v2_soap/?wsdl'); // TODO : change url
$sessionId = $proxy->login('yourapiuser', 'apiuserpassword'); // TODO : change login and pwd if necessary

    $categoryIds = array();

    //prepare the initial attributes array required to upload
    $attrbutesFinal = array(

            'name' => '',
            'is_active' => 1,
            'position' => 1,
            'available_sort_by' => array('position'),
            'custom_design' => null,
            'custom_apply_to_products' => null,
            'custom_design_from' => null,
            'custom_design_to' => null,
            'custom_layout_update' => null,
            'default_sort_by' => 'position',
            'description' => '',
            'display_mode' => null,
            'is_anchor' => 0,
            'landing_page' => null,
            'meta_description' => ' ',
            'meta_keywords' => ' ',
            'meta_title' => ' ',
            'page_layout' => '',
            'url_key' => '',
            'include_in_menu' => 1,
    );


        $fileURL = $target_file;
        //$content = file_get_contents($fileURL, false);
        $content = file($fileURL);

        $rowCount = 0;
        foreach ($content as $row){

            $row = str_replace("\r\n", "", $row);
            $rowAsArray = explode(",", $row);

            if($rowCount === 0){
                //we collect the header row here and keep it separate
                $headerRow = $rowAsArray;
                $columns = count($headerRow);
            }else{

                for ($i = 0; $i < $columns; $i++) {
                    //an associative array is created with header row columns as keys and 
                    //columns of subsequent rows as values
                    //This is the format required by the web service as well
                    if ($headerRow[$i] === 'available_sort_by'){
                        //THIS COLUMN NEEDS AN ARRAY
                        $attrbutesFinal[$headerRow[$i]] = array($rowAsArray[$i]);
                    }else {

                        $attrbutesFinal[$headerRow[$i]] = $rowAsArray[$i];
                    }

                }
                //create category ---> SOAP call
                //if parent calumn has the ID (checked if it is number or not by calling intval() ) then
                //call soap directly using it as 'parent'
                if (intval($attrbutesFinal['parent']) > 1){

                    $result = $proxy->catalogCategoryCreate($sessionId, intval($attrbutesFinal['parent']), $attrbutesFinal);
                }else {

                    foreach ($categoryIds as $key => $val){

                        if ($attrbutesFinal['parent'] === $key){
                            $result = $proxy->catalogCategoryCreate($sessionId, intval($val), $attrbutesFinal);
                        }
                    }
                }
                if ($result > 0){

                    //File contains category name as parent but the web service needs the 
                    //ID.  while uploading new categories, we do not know the category ids yet
                    //So, once the category is created, we collect its ID here
                    $categoryIds[$attrbutesFinal['name']] = $result;
                }
            }

            //var_dump($rowAsArray);

            $rowCount += 1;
        }

        echo "<strong>Categories created ===> </strong></br>";
        var_dump($categoryIds);
?>

Here, once the parent category is created, I collect the entity ID created and use it to create its children.

I use the csv file with below data:

name parent description HEALTH AND COSMETICS 63 HEALTH AND COSMETICS HAIR CARE HEALTH AND COSMETICS HAIR CARE

IT assumes that I know entity ID of one category, root or some category below the root. This works for me. But, I think this can be made more efficient.

Thank you Dhananjay

Upvotes: 0

Zahirabbas
Zahirabbas

Reputation: 1119

$category = Mage::getModel('catalog/category');
$category->setStoreId(0); // 0 = default/all store view. If you want to save data for a specific store view, replace 0 by Mage::app()->getStore()->getId().

//if update
if ($id) {
  $category->load($id);
}

$general['name'] = "My Category";
$general['path'] = "1/3/"; // catalog path here you can add your own ID
$general['description'] = "Great My Category";
$general['meta_title'] = "My Category"; //Page title
$general['meta_keywords'] = "My , Category";
$general['meta_description'] = "Some description to be found by meta search robots. 2";
$general['landing_page'] = ""; //has to be created in advance, here comes id
$general['display_mode'] = "PRODUCTS"; //static block and the products are shown on the page
$general['is_active'] = 1;
$general['is_anchor'] = 0;
$general['page_layout'] = 'two_columns_left';

//$general['url_key'] = "cars";//url to be used for this category's page by magento.
//$general['image'] = "cars.jpg";


$category->addData($general);

try {
    $category->setId(255); // Here you cant set your own entity id
    $category->save();
    echo "Success! Id: ".$category->getId();
}
catch (Exception $e){
    echo $e->getMessage();
}

Upvotes: 2

Related Questions