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
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();
I think it's the best solution, that it handle set names and link_rewrite to multiple PS langages
$object = new Category();
$link = Tools::link_rewrite( $category);
$object->name = array();
$object->link_rewrite = array();
foreach (Language::getLanguages(false) as $lang){
$object->name[$lang['id_lang']] = $category ;
$object->link_rewrite[$lang['id_lang']] = $link;
}
$object->id_parent = $parent_id;
$object->save();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With