Jump to content

[SOLVED] Category add by code


tarek.fellah

Recommended Posts

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();

but it show me an 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

It seems that it is related to name field but it is assigned by 

$object->name = "xcvxvvx";

Any help please,

 

Thanks.

Edited by vekia (see edit history)
Link to comment
Share on other sites

You need to handle multi-language fields like this:
 

foreach (Language::getLanguages(false) as $lang){
  $object->name[$lang['id_lang']] = 'xcvxvvx';
}

also, you don't have to assign id_category, that should be handled automatically. Something like this should be ok:

if (!$parent_id){
  $parent_id = Configuration::get('PS_HOME_CATEGORY');
}
$object = new Category();
$link = Tools::link_rewrite('xcvxvvx');
$object->name = array();
$object->link_rewrite = array();
foreach (Language::getLanguages(false) as $lang){
  $object->name[$lang['id_lang']] = 'xcvxvvx';
  $object->link_rewrite[$lang['id_lang']] = $link;
}
$object->id_parent = $parent_id;
$object->save();

(haven't tested but should give you an idea)

Edited by jgullstr (see edit history)
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...