add category programmatically prestashop

假装没事ソ 提交于 2019-12-05 11:52:23

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

When ever you try to add category like this or a product like this you will get such errors, i dont know why as i myself got such errors while importing data from other system like drupal. $c is nothing just another array of values i have, which has all the category related data. You should assing your related data to each array element.

You should do it as below:

        $data['id_parent'] = $c['id_parent'];
        $data['id_shop_default'] = 1;
        $data['active'] = $c['active'];
        $data['date_add'] = $c['date_add'];
        $data['date_upd'] = $c['date_upd'];
        $data['position'] = $c['position'];

        $datal['id_category'] = $id_category;
        $datal['id_shop'] = 1;
        $datal['id_lang'] = 1;
        $datal['name'] = pSQL($c['name']);
        $datal['description'] = pSQL($c['description']);
        $datal['link_rewrite'] = pSQL($c['link_rewrite']);
        $datal['meta_title'] = pSQL($c['meta_title']);
        $datal['meta_keywords'] = pSQL($c['meta_keywords']);
        $datal['meta_description'] = pSQL($c['meta_description']);

        $dataShop['id_category'] = $id_category;
        $dataShop['id_shop'] = 1;
        $dataShop['position'] = $c['position'];

        if(!DB::getInstance()->insert('category', $data))
            die('Error in category insert : '.$c['id_category']);
        if(!DB::getInstance()->insert('category_lang', $datal))
            die('Error in category lang insert : '.$c['id_category']);
        if(!DB::getInstance()->insert('category_shop', $dataShop))
            die('Error in category shop insert : '.$c['id_category']);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!