Reputation: 507
So I've been dealing with this problem for quite some time and can't find a clear solution. So basically I'm adding new products directly into db using Product object. For now it went well but I can't manage to link new products with a category.
$cat_ids = [];
foreach ($value['kat_naziv'] as $cat_val) {
$cat_ids[] = (int)$luceed->selectCategoryIds($cat_val)[$cat_val]['id_category'];
}
$product->id_category = 3;
$product->id_category_default = 3;
$product->save();
$product->addToCategories($cat_ids);
So basically $cat_ids is an array of integers that i'm getting from db where name is something i pass as a parameter to selectCategoryIds;
What is the problem here why it wont associate newly created product with categories i give to it
Upvotes: 3
Views: 1978
Reputation: 9886
Version (1.6)
I found the following bug in Product.php
, in addToCategories
, search for if (!in_array($new_id_categ, $current_categories))
(line 964),
notice that the if
is missing {}
- add them, and the problem is solved:
foreach ($categories as $new_id_categ) {
if (!in_array($new_id_categ, $current_categories)) {
if ($position == null) {
$position = (int)$new_categ_pos[$new_id_categ];
}
$product_cats[] = array(
'id_category' => (int)$new_id_categ,
'id_product' => (int)$this->id,
'position' => $position,
);
}
}
Prestashop developer LOVEs omitting {}
after if
and foreach
- this is supper annoying and bug prone.
This issue is fixed in the repo: https://github.com/PrestaShop/PrestaShop/blob/1.6.1.x/classes/Product.php
NOTE: this solution solves the bug in the following scenario - a product that is already link to a category is link to another category (while keeping the original category)
although I'm not sure if this is the scenario in the question.
Upvotes: 0
Reputation: 507
@FMEModule That's exactly what i did there but i've filled the array with the id's of categories from the database
Anyways I ended up writing my own queries for associatting products with categories
Upvotes: 0
Reputation: 126
After creating your new product ( i.e $product = new Product() ). You can assign categories to product using.
$product->updateCategories($category_array);
where
$category_array = array("0" => "2", "1" => "3", "4" => "6"...... );
Upvotes: 2