Jump to content

Custom create product function


drasl
 Share

Recommended Posts

Hi all!

I'm actually working on my own function to create product, because I have multiple shops in prestashop with different names, diferent hosts and same products.

That's why I need to design a product form to create/modify/delete products.

I'm now stucked in the point that I don't know how to create the product TAGS, I tested like this:

$product->tags = array('test1','test2');

$product->tags = 'test1,test2');

But the tags won't be created.

I will paste my code here and I will update it:

 

	public function createProduct($product_array){ //Array con todas las variables de producto

		$error = "";
		Shop::setContext(Shop::CONTEXT_ALL);
		
		$product = new Product();
		$product->ean13					= $product_array['ean13'];		
		$product->name 		    		= $product_array['name'];			
		$product->link_rewrite  		= $product_array['link_rewrite'];
		$product->id_category 			= $product_array['id_category'];
		$product->id_category_default   = $product_array['id_category_default'];
		$product->redirect_type 		= $product_array['redirect_type'];
		$product->price 				= $product_array['price'];
		$product->id_tax_rules_group	= $product_array['id_tax_rules_group'];
		$product->quantity 				= $product_array['quantity'];
		$product->minimal_quantity 		= $product_array['minimal_quantity'];
		$product->show_price 			= $product_array['show_price'];
		$product->active 				= $product_array['active'];
		$product->online_only			= $product_array['online_only'];
		$product->meta_keywords 		= $product_array['meta_keywords']; 
		$product->meta_description 		= $product_array['meta_description']; 
		$product->is_virtual 			= $product_array['is_virtual']; 
		$product->weight				= $product_array['weight'];
		$product->referende 			= $product_array['reference'];
		$product->id_manufacturer		= $product_array['id_manufacturer'];		

		if ($product->add()){
			$product->updateCategories($product->id_category);
			StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);			

			//Crea imágenes
			foreach ($product_array['images'] as $product_image){	
				$cover = $product_image[0];
				$url = $product_image[1];
				$id_product = $product->id;
				$image = new Image();
				$image->id_product = $id_product;
				$image->position = Image::getHighestPosition($id_product) + 1;
				$image->cover = $cover;
				if (($image->validateFields(false, true)) === true && ($image->validateFieldsLang(false, true)) === true && $image->add()){
				    $image->associateTo(Context::getContext()->shop->id);
				    if (!$this->copyImg($id_product, $image->id, $url, 'products')){
				        $image->delete();
				        $error .= "<li>Ha ocurrido un fallo con la imágen</li>";
				    }
				}
			}	
			
			echo "Producto con ID: ".$id_product." creado correctamente!";
		}else{
			$error .= "<li>Ha ocurrido un error al crear el producto";
		}		

	}

 

Thanks in advance!

Share this post


Link to post
Share on other sites

Done. The solution:

foreach ($product_array['tags_array'] as $lang => $lang_tags){				
	Tag::addTags($lang, $product->id, $lang_tags);
}

Now I update my code if someone need it:

	public function createProduct($product_array){
		/******** Example argument $product_array ********/
		/*
		$product_array['ean13'] = 9999999;		
		$product_array['name'] = [3 => 'Prueba producto',4 => 'Prueba producto portugal'];			
		$product_array['link_rewrite'] = [3 => 'prueba_producto', 4 => 'prueba_producto_portugal'];
		$product_array['id_category'] = [2,3];
		$product_array['id_category_default'] = 2;
		$product_array['redirect_type'] = '404';
		$product_array['wholesale_price'] = 0;
		$product_array['price'] = 0;
		$product_array['id_tax_rules_group'] = 9;
		$product_array['quantity'] = 2;
		$product_array['minimal_quantity'] = 1;
		$product_array['show_price'] = 1;
		$product_array['active'] = 0;
		$product_array['online_only'] = 1;
		$product_array['meta_keywords'] = 'test';
		$product_array['meta_description'] = 'test';
		$product_array['is_virtual'] = 0;
		$product_array['weight'] = 2;
		$product_array['reference'] = 'ASD';
		$product_array['id_manufacturer'] = 1;
		$product_array['images'][] = array(true,'url'); // $cover, $url
		$product_array['images'][] = array(false,'url'); // $cover, $url
		// Variables de combinación 
		$product_array['combinations'][1]['id_image'] = 1; //Imágen del producto correspondiente a esta combinación
		$product_array['combinations'][1]['wholesale_price'] = 0;
		$product_array['combinations'][1]['price'] = 5;
		$product_array['combinations'][1]['weight'] = 3;
		$product_array['combinations'][1]['quantity'] = 2;
		$product_array['combinations'][1]['reference'] = 'referencia_combinacion';
		$product_array['combinations'][1]['ean13'] = '1234567890123';
		$product_array['combinations'][1]['default_on'] = true;
		$product_array['combinations'][1]['upc'] = "";
		$product_array['combinations'][1]['minimal_quantity'] = 1;
		// Atributos de combinación 
		$product_array['combinations'][1]['combination_attributes'][] = 25;
		$product_array['combinations'][1]['combination_attributes'][] = 26;
		*/		
		
		//Creating the product	
		Shop::setContext(Shop::CONTEXT_ALL);
		$error = "";
		
		$product = new Product();
		$product->ean13					= $product_array['ean13'];		
		$product->name 		    		= $product_array['name'];			
		$product->link_rewrite  		= $product_array['link_rewrite'];
		$product->id_category 			= $product_array['id_category'];
		$product->id_category_default   = $product_array['id_category_default'];
		$product->redirect_type 		= $product_array['redirect_type'];
		$product->wholesale_price		= $product_array['wholesale_price'];
		$product->price 				= $product_array['price'];
		$product->id_tax_rules_group	= $product_array['id_tax_rules_group'];
		$product->quantity 				= $product_array['quantity'];
		$product->minimal_quantity 		= $product_array['minimal_quantity'];
		$product->show_price 			= $product_array['show_price'];
		$product->active 				= $product_array['active'];
		$product->online_only			= $product_array['online_only'];
		$product->meta_keywords 		= $product_array['meta_keywords']; 
		$product->meta_description 		= $product_array['meta_description']; 
		$product->is_virtual 			= $product_array['is_virtual']; 
		$product->weight				= $product_array['weight'];
		$product->referende 			= $product_array['reference'];
		$product->id_manufacturer		= $product_array['id_manufacturer'];				

		if ($product->add()){
			$product->updateCategories($product->id_category);
			StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);
			//Añado los tags				
			foreach ($product_array['tags_array'] as $lang => $lang_tags){				
				Tag::addTags($lang, $product->id, $lang_tags);
			}

			//Crea imágenes
			foreach ($product_array['images'] as $product_image){	
				$cover = $product_image[0];
				$url = $product_image[1];
				$id_product = $product->id;
				$image = new Image();
				$image->id_product = $id_product;
				$image->position = Image::getHighestPosition($id_product) + 1;
				$image->cover = $cover;
				if (($image->validateFields(false, true)) === true && ($image->validateFieldsLang(false, true)) === true && $image->add()){
				    $image->associateTo(Context::getContext()->shop->id);
				    if (!$this->copyImg($id_product, $image->id, $url, 'products')){
				        $image->delete();
				        $error .= "<li>Ha ocurrido un fallo con la imágen</li>";
				    }
				}
			}

			//Creo combinaciones			
			$id_shop_list = array(1,2);			
            $id_product_attribute = $product->addCombinationEntity(
                (float)$product_array['combinations'][1]['wholesale_price'],
                (float)$product_array['combinations'][1]['price'],
                (float)$product_array['combinations'][1]['weight'],
                0,
                0,
                (int)$product_array['combinations'][1]['quantity'],
                $product_array['combinations'][1]['id_image'],
                strval($product_array['combinations'][1]['reference']),
                0,
                strval($product_array['combinations'][1]['ean13']),
                (int)$product_array['combinations'][1]['default_on'],
                0,
                strval($product_array['combinations'][1]['upc']),
                (int)$product_array['combinations'][1]['minimal_quantity'],
                $id_shop_list                
            );		

            // Si la combinación se ha creado correctamente...
            if ($product->productAttributeExists($id_product_attribute)){
            	//Creo atributos
            	if (!$product->addAttributeCombinaison($id_product_attribute, $product_array['combinations'][1]['combination_attributes'])){
            		$error = "<li>Ocurrió un problem al crear el/los atributo/s para la combinacón";
            	}else{
            		StockAvailable::setQuantity((int)$product->id, $id_product_attribute, (int)$product_array['combinations'][1]['quantity'], Context::getContext()->shop->id);
            	}
            }else{
            	$error .= "<li>Ocurrió un error al crear la combinación!";
            }
			
			echo "Producto con ID: ".$id_product." creado correctamente!";
		}else{
			$error .= "<li>Ha ocurrido un error al crear el producto";
		}

		// Si no hay errores, creo producto en tienda remota.
		if ($error != ""){	
			return true;
		}else{
			return $error;
		}

	}

 

Edited by lsard (see edit history)
  • Like 2

Share this post


Link to post
Share on other sites

  • 2 years later...

StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id)

That code line sets the "quantity" to 0 in each product created. Is it totally necessary?

My own script seems to work fine without this line

(commented)--> //StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id)

thanks.

edition:

OK I'm sorry, the code works fine in a INSERT new product, but dont't work in my script in a UPDATE product.

thanks.

Edited by jordinur
correction (see edit history)

Share this post


Link to post
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
 Share

×
×
  • Create New...

Important Information

Cookies ensure the smooth running of our services. Using these, you accept the use of cookies. Learn More