add category programmatically prestashop

Tarek Fellah picture Tarek Fellah · Sep 10, 2013 · Viewed 11.2k times · Source

I would like to add categories programmatically to prestashop, i tried this code

$object = new Category();

$object->name = "xcvxvvx";
if (!$parent_id){
$parent_id = Configuration::get('PS_HOME_CATEGORY');
}
$object->id_parent = $parent_id;
$object->link_rewrite = array((int)(Configuration::get('PS_LANG_DEFAULT')) =>   $category);
$object->add();
$object->id_category = $object->id;

$object->id_category_default = $object->id;

$object->update();

I get this error message :

Fatal error: Uncaught exception 'PrestaShopException' with message 'Property
Category->name is empty' in /var/www/autospareparts.se.com/classes/ObjectModel.php:874
Stack trace:
#0 /var/www/autospareparts.se.com/classes/ObjectModel.php(306):   
ObjectModelCore->validateFieldsLang()
#1 /var/www/autospareparts.se.com/classes/ObjectModel.php(490):  
ObjectModelCore->getFieldsLang()
#2 /var/www/autospareparts.se.com/classes/Category.php(157): 
ObjectModelCore->add(true,  false)
#3 /var/www/autospareparts.se.com/get_product.php(51): CategoryCore->add()
#4 {main}
thrown in /var/www/autospareparts.se.com/classes/ObjectModel.php on line 874

error related to name field that i assigned

$object->name = "xcvxvvx";

Thanks in advance

Answer

romainberger picture romainberger · Sep 10, 2013

It's because of the internationalization. The ObjectModel class needs an array for the name, exactly like the link_rewrite.

Working code (tested on 1.5.4.1 but should work on >=1.5)

$object = new Category();
$object->name = array((int)Configuration::get('PS_LANG_DEFAULT') => 'Cool name');
$object->id_parent = Configuration::get('PS_HOME_CATEGORY');
$object->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  'cool-url');
$object->add();