I'm trying to make a csv export script, for a partener price aggregation sistem. i'm having trouble extracting the weight of the products from magento.
$show_prodweight = (#$_GET['weight'] == "on") ? "on" : "off";
....
$product = Mage::getModel('catalog/product');
$product->setStoreId($storeId);
$product->load($product_id);
$prod_model = $product->getSku();
$prod_id = $product->getId();
$prod_name = $product->getName();
if ( $show_prodweight =="on") {
$prod_weight = $product->getWeight ();
}
else {
$prod_weight == "2";
}
....
print $PRODUCT['prod_weight'] . $datafeed_separator .
Can someone please tell me what i am doing wrong ?
resolved it by simplyfing code
$product = Mage::getModel('catalog/product');
$product->setStoreId($storeId);
$product->load($product_id);
$prod_model = $product->getSku();
$prod_id = $product->getId();
$prod_name = $product->getName();
$prod_weight = $product->getWeight();
Related
When added from a third-party product to the cart. I want to change the quantity of goods in the basket. Get alert Product (........ ) is over.
if(is_array($arCartPrice)){
//if($arCartPrice['OPTIONS']['MINIMUM']>1){$QUANTITY=$arCartPrice['OPTIONS']['MINIMUM'];}else{$QUANTITY=1;}
$QUANTITY=$arCartPrice['AVAILABLE_NUM'];
$DefaultCategory = 12;
$DefaultTaxGroup = 0;
$Price = $arCartPrice['PRICE_CONVERTED'];
$PriceVAT = round($Price);
$Reference = $arCartPrice['ARTICLE'].' / '.$arCartPrice['BRAND'];
//Presta init
global $context;
if(!$context){$context = Context::getContext();}
$logged = $context->cookie->__get('logged');
$id_cart = $context->cookie->__get('id_cart');
$id_lang = $context->cookie->__get('id_lang');
$id_guest = $context->cookie->__get('id_guest');
$id_currency = $context->cookie->__get('id_currency');
// Add cart if no cart found
if (!$id_cart){
$context->cart = new Cart();
$context->cart->id_customer = $context->customer->id;
$context->cart->id_currency = $id_currency;
$context->cart->add();
if($context->cart->id){
$context->cookie->id_cart = (int)$context->cart->id;
}
$id_cart = (int)$context->cart->id;
}
$doAdd="Y";
//if(!$logged>0){$doAdd="N"; $TCore->arErrorMessages[] = 'You must be logged in to buy products';}
//if(trim($Reference)=='' OR !$Price>0 OR !$QUANTITY>0){$doAdd="N"; $TCore->arErrorMessages[] = 'Add to cart data is missing!';}
if(!$id_cart>0){$doAdd="N"; ErAdd("Your cookie <b>id_cart</b> is wrong!",1);}
if(!$id_lang>0){$doAdd="N"; ErAdd("Your cookie <b>id_lang</b> is wrong!",1);}
if($doAdd!="N"){
//Check avail. tecdoc item in Presta
$sql = 'SELECT p.`id_product`, pl.`name` FROM `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product`)
WHERE pl.`id_lang` = '.$id_lang.' AND
p.`price` = '.$Price.' AND
p.`reference` = "'.$Reference.'"
';
$arRes = Db::getInstance()->executeS($sql);
if(count($arRes)>0){
$NewTID = $arRes[0]['id_product'];
}else{
//Supplier data (for 1C integration)
$supplierName = $arCartPrice['SUPPLIER_STOCK'];
$supplierId = $suppliers = (Supplier::getIdByName($supplierName));
if (!$supplierId) {
$supplier = new Supplier();
$supplier->name = $supplierName;
$supplier->active = 1;
$supplier->add();
$supplierId = $supplier->id;
}
$obProduct = new Product(false,false,$id_lang);
$obProduct->id_category_default = $DefaultCategory;
$obProduct->unity = $arCartPrice['ADD_URL'];
$obProduct->name = $arCartPrice['ARTICLE'] .' / '.substr($arCartPrice['NAME'],0,400).' / '.$arCartPrice['BRAND'];
$obProduct->description = 'This product is created automatically by ';
$obProduct->description_short = $arCartPrice['SUPPLIER_STOCK'].' ['.$arCartPrice['DAY'].' days]';
$obProduct->price = $Price;
$obProduct->wholesale_price = $arCartPrice['PRICE'];
$obProduct->reference = $Reference;
$obProduct->link_rewrite = $arCartPrice['CPID'];
$obProduct->available_for_order = 1; //true
$obProduct->visibility = 'none';
$obProduct->is_virtual = 0;
//$obProduct->weight = round($arCartPrice['OPTIONS']['WEIGHT']/1000,2);
$obProduct->minimal_quantity = 1;
$obProduct->condition = 'used';
$obProduct->condition = 'refurbished';
$obProduct->available_now = $arCartPrice['AVAILABLE_NUM'];
$obProduct->quantity = $arCartPrice['AVAILABLE_NUM'];
//supplier
$obProduct->supplier_name = $supplierName;
$obProduct->id_supplier = $supplierId;
$obProduct->id_tax_rules_group = $DefaultTaxGroup;
//echo '<br><pre>';print_r($obProduct);echo '</pre>';die();
$obProduct->add();
if($obProduct->id>0){
$NewTID = $obProduct->id;
$obProduct->setWsCategories(Array(Array("id"=>$DefaultCategory)));
//Add image
if($arCartPrice['IMG_SRC']!='' AND $NewTID>0){
$shops = Shop::getShops(true, null, true);
$image = new Image();
$image->id_product = $NewTID;
$image->position = Image::getHighestPosition($NewTID)+1;
$image->cover = true; // or false;
if(($image->validateFields(false, true)) === true && ($image->validateFieldsLang(false, true)) === true && $image->add()){
$image->associateTo($shops);
$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
if(Tools::copy($arCartPrice['IMG_SRC'], $tmpfile)){
$path = $image->getPathForCreation();
ImageManager::resize($tmpfile, $path.'.jpg');
}
unlink($tmpfile);
}
}
}else{
ErAdd("Prestashop new Item ID is false",1);
}
unset($obProduct);
}
if($NewTID>0){
//if($arCartPrice['AVAILABLE']>0){StockAvailable::setQuantity($NewTID, false, $arCartPrice['AVAILABLE']);}
StockAvailable::setQuantity($NewTID, 0, (int) $arCartPrice['AVAILABLE']);
$obCart = new Cart($id_cart);
$obCart->id_lang = $id_lang;
$obCart->id_currency = $id_currency;
if($obCart->updateQty((int)$QUANTITY=1, (int)$NewTID)){
Header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); die();
}else{
ErAdd(" Add to Cart is false. NewTID=".$NewTID,1);
}
How to fix the code so you can update the quantity of goods in your cart.
And the number of 10 pieces. 1 piece is added to the cart. I want to add more to my cart. How to implement it? When I add 2 pieces. I receive a message Product (........ ) is over..
enter image description here
First of all, after you created the product, check in the Backoffice if the quantity is well stored (If the newly created product quantity is equal with $arCartPrice['AVAILABLE_NUM'] )
Maybe you can try with enabled "Allow ordering when out of stock" .
How to update cart item using item ID ? I have searched a lot but could not success, here is my codes -
require_once '../app/Mage.php';
Mage::app('default');
$qty = $_REQUEST['quantity'];
$item_id = (int) $_REQUEST['item_id'];
$cart = Mage::getSingleton('checkout/cart');
$quoteItem = $cart->getQuote()->getItemById($item_id);
/*$quoteItem = Mage::getModel('sales/quote_item')->getCollection()
->addFieldToFilter('item_id', array('in' => array($item_id)));*/
print_r($quoteItem);
if (!$quoteItem) {
Mage::throwException('Quote item is not found.');
}
if ($qty == 0) {
$cart->removeItem($id);
} else {
$quoteItem->setQty($qty)->save();
}
$cart->save();
I am implementing it in API , however same code is working fine in website.Please help!!!
I used the below code to update cart items and I am using observer to do that. can you please try this.
$quote = $observer->getEvent()->getQuote();
var_dump($quote->getId());
$quote = Mage::getSingleton('checkout/session')->getQuote();
//var_dump($quote->getId());
$cartItems = $quote->getAllItems();
//$storeId = Mage::app()->getStore()->getId();
foreach ($cartItems as $item) {
//echo $item->getSku();
$item->set__($value); // desired quote field from database
$item->save();
}
$quote->save();
This is the code so far.
I know its not very secure for injections, I'll take care of that later.
but my problem is that my cart adds product but sometimes i get the:
Unsupported operand types in E:\HostingSpaces\Knoppers1\topjop.nl\wwwroot\portal\core\tj_functions.php on line 358
error and i can't add multiple items of the same type.
line 358: $_SESSION['cart'][$uid] += 1;//
Maybe some of you know because other related questions didn't helped me.
function toevoegen(){
session_start();
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
if(isset($_GET['add'])) {
$info = 'U heeft een product toegevoegd <META HTTP-EQUIV=REFRESH CONTENT="1; URL=http://topjop.nl/portal/winkelmandje.php">';
$uid = 0; //update id
foreach($_SESSION['cart'] as $id => $data){
if($data[0]==$_GET['add']){
$uid = $id;//
}
}
if($uid == 0){
array_push($_SESSION['cart'],array($_GET['add'],1));//
}else{
$_SESSION['cart'][$uid] += 1;//
}
}
else {
$info = '';
}
return $info;
}
function winkelmandje(){
mysql_connect("mysql8.mijnhostingpartner.nl","","");
mysql_select_db("Knoppers1_portal");
session_start();
$mand = '<table id="winkelmandje_tabel"><tr><td>Product</td>
<td>Stukprijs</td><td>Aantal</td><td>Totaal bedrag</td><td></td></tr>';
foreach($_SESSION['cart'] as $data){
$id = $data[0];//
$value = $data[1];//
if($value>0){
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$totaal = $get_row['price']*$value;
$totaalprijs = number_format($totaal,2,',','.');
$mand .= '<tr><td>'.$get_row['name'].'</td>
<td>€'.$get_row['price'].'</td><td>'. $value .'</td> <td>€'.$totaalprijs.'</td></tr>';
}
}
else{
}
}
$aantal = '';
$kosten = '';
return $mand.'<tr><td><b>Totaal:</b></td><td></td><td><b>'. $aantal .'</b></td><td><b>'. $kosten .'</b></td></tr></table>';
}
toevoegen = ADD<br>
winkelmandje = SHOPPINGCART
Seems like $_SESSION['cart'][$uid] is an array containing id and value as you read it like that in the follwoing snippet:
$id = $data[0];//
$value = $data[1];//
it seems $_SESSION['cart'][$uid] is an array. so you can't do +=1
maybe do
$_SESSION['cart'][$uid][1] += 1; // increment $value
How to echo all custom options with all the values by product id for Magento?
If i am using this code...
public function ws_productdetail($store_id, $service, $productid)
{
$res=array();
$productsCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('entity_id', array('in' => $productid))
->addAttributeToSelect('*');
$all_product_images = array();
$product = Mage::getModel('catalog/product')->load($productid);
foreach ($product->getMediaGalleryImages() as $image) {
$all_product_images[] = $image->getUrl();
}
foreach($productsCollection as $product)
{
$res["id"] = $product->getId();
$res["name"] = $product->getName();
$res["price"] = number_format($product->getPrice(),2);
}
return($res);
}
... how can I get the custom options?
For example say for a product JEANS, COLOR with various values {blue,black,brown} and every option will have different prices, then how i get all this information as output.
According to my understanding, you want to show the all DROPDOWN custom option on view page then try this.
$productid = $_product->getId(); //PLEASE ENTER THE PRODUCT ID HERE
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
foreach($attVal as $optionKey => $optionVal)
{
$optStr.='<dl><div class="custom_select_css">
<dt><label>'.$optionVal->getTitle().'</label></dt>
<dd class="last">
<div class="input-box">';
$optStr.= "<select id='".$optionVal->getId()."' name='options[".$optionVal->getId()."]'>";
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$price = number_format($valuesVal->getPrice(),0);
$optStr.= "<option price='".number_format($valuesVal->getPrice(),0)."' data-label='".$colorarray[$valuesVal->getTitle()]."' value='".$valuesVal->getId()."'>".$valuesVal->getTitle(); if($price != '0'){$optStr.=" +$".number_format($valuesVal->getPrice(),2);}$optStr.=" </option>";
}
$optStr.= "</select></div></dd><div></dl>";
}
echo $optStr;
------------------------------ UPDATED CODE -------------------------------
public function ws_customdetail ($productid)
{
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal)
{
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;
}
$inc++;
}
return $all_custom_option_array;
}
Use ws_customdetail function and pass the product id in it.
THIS IS THE EXACT CODE THAT WORKED FOR ME.
public function customdetail($productid){
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal){
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$all_custom_option_array[$inc]['custom_option_type']=$optionVal->getType();
$all_custom_option_array[$inc]['custom_option_value_array'];
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal){
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;}
$inc++;}
return $all_custom_option_array;}
HOPE THIS WILL HELP SOMEONE :)
THANX
i'm trying to build a feed generator based on this post Magento: Product data extraction for product feed. for the time beeing my problem is with the categories and subcategories of the product.
my code:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
define('SAVE_FEED_LOCATION','feed/compari.csv');
//$objDateTime = new DateTime('NOW');
require 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('status', 1); //1 is set to select product in stock
$products->addAttributeToFilter('visibility', 4); //4 is set to select active products
$products->addAttributeToSelect('*');
$prodIds=$products->getAllIds();
$product = Mage::getModel('catalog/product');
$counter = 0;
$feedaray=[];
foreach($prodIds as $productId) {
if (++$counter < 500000){
$product->load($productId);
$title_temp = $product->getName();
if (strlen($title_temp) > 255){
$title_temp = str_replace("Supply", "", $title_temp);
$title_temp = str_replace(" ", " ", $title_temp);
} //$title_temp will hold the product name
$maincat = $subcats = '';
$categoryCollection = $product->getCategoryCollection();
if i do a var_dump($title_temp.' categorie: '.$categorie_id);
foreach($categoryCollection as $cat){
$categorie_id=$cat->getData()['entity_id'];
$_cat_ac = Mage::getModel('catalog/category')->load($categorie_id);
if($subcats_ac == ''){
$maincat_ac = $subcats_ac = $_cat_ac->getName();
}else {
$subcats_ac .= ">".$_cat_ac->getName();
}
echo '<pre>';
var_dump($title_temp.' categorie: '.$categorie_id);
echo '</pre>';
}
i'm geting the corect result:
string(59) "product 1 categorie: 3" - prime category
string(60) "product 1 categorie: 37" - sub category
string(45) "product 2 categorie: 4" - prime category
string(46) "product 2 categorie: 21" - sub category
further i need to prepare the data for exporting to csv, and i do it like this:
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$product_data = array();
$product_data['ProductID'] = $productId;
$product_data['ProductName'] = substr(iconv("UTF-8","UTF-8//IGNORE",$title_temp), 0, 255);
$product_data['SKUnumber'] = $product->getSku();
$product_data['PrimaryCategory'] = $maincat_ac; //this is spitting same data for all products
$product_data['SecondaryCategory'] = $subcats_ac; //this is spitting same data for all products
$product_data['ProductURL'] = $StoreURL.$product->getUrlPath(); //$StroeURL is set as a string
$product_data['ProductImageURL'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
$product_data['ShortProductDescription'] = substr(iconv("UTF-8","UTF-8//IGNORE",$product->getDescription()), 0, 80)."...";
$product_data['LongProductDescription'] = substr(iconv("UTF-8","UTF-8//IGNORE",$product->getDescription()), 0, 2000);
$product_data['SalePrice'] = round($product->getFinalPrice(),2);
$product_data['RetailPrice'] = round($product->getPrice(),2);
$product_data['ManufacturerName'] =$product->getAttributeText('manufacturer');
$product_data['Quantity'] = round($stock->getQty(),2);
$product_data['Currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
foreach($product_data as $k=>$val){
$bad=array('"',"\r\n","\n","\r","\t");
$good=array(""," "," "," ","");
$product_data[$k] = str_replace($bad,$good,$val);
}
$feedaray[]=$product_data;
echo $counter . " ";
}
}
$handle=fopen(SAVE_FEED_LOCATION, 'w');
foreach ($feedaray as $fields) {
fputcsv($handle, $fields);
}
fclose($handle);
?>
the problem is with the maincat_ac and subcat_ac that are not displaing corect data.
solution for the problem
$cats=[];
foreach($categoryCollection as $cat){
$cats[]=$cat->getData()['entity_id'];
}
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
if($subcats == ''){
$maincat = $subcats = $_cat->getName();
}else {
$subcats .= ">".$_cat->getName();
}
}
may be it isn't the best solution. if you have another idea please share.
regards