Jump to content

Add product programmatically not working


Recommended Posts

Hello,

I have a webservice where i import the categories and product.

Categories are working correctly but products are not shown in the backoffice (They are on the database).

My code looks like this:

 

Any idea what i'm missing ?

<?php
namespace Magana\Import;
 
use Db;
use Context;
use Product;
use Configuration;
use StockAvailable;
use Magana\Tools\Tool;
use Mgana\Tools\MessageObj;
 
class Products
{
private $output;
private $url_data = "http://data.magana.dev.hexis.fr/export/products/json/";
public function __construct($dos)
{
$this->url_data .= $dos;
$prods = Tool::getData($this->url_data);
$lang = Configuration::get('PS_LANG_DEFAULT');
foreach ($prods as $key => $prod) {
$metas = unserialize($prod->metas);
$product = new Product();
$product->reference = $metas->reference;
$product->name = [$lang => $prod->title];
$product->link_rewrite = [$lang => Tool::slugyfy($prod->title)];
$product->description = array($lang => $prod->desc);
$product->minimal_quantity = 1;
$product->redirect_type = '301-category';
$product->on_sale = 0;
$product->show_price = 1;
$product->price = 13.90;
$product->quantity = 70;
 
if ($metas->parent) {
$sql = "SELECT `id_category` FROM `"._DB_PREFIX_."category` WHERE erp_id= {$metas->parent}";
$res = Db::getInstance()->executeS($sql);
if ($res) {
foreach ($res as $row) {
$product->id_category[] = $row['id_category'];
}
}
$product->id_category_default = 2;
}
$product->add();
$product->addToCategories($product->id_category);
StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);
 
 
}
$msg = ['products' => count($prods)];
MessageObj::add($msg, 'added');
}
 
}
Edited by maganapro (see edit history)
Link to comment
Share on other sites

Problem solved...

$product->id_category was null... Set default to PS_HOME_CATEGORY 

$product->id_category_default = $product->id_category[0] ?: Configuration::get('PS_HOME_CATEGORY');
$product->add();
$product->addToCategories($product->id_category_default);
  • 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...