I am trying to create order programatically. Which is happening perfectly fine. I just don't know how to set discount amount programmatically. which is going to be different for different orders.
You can add a custom price to a product when you add it into the quote using this:
$custom_price = 100; //Products new price for the specific order/customer.
$qty = 1;
$product_id = 210;
$product = Mage::getModel('catalog/product')->load($product_id);
$quoteItem = $quote->addProduct($product, $qty);
$quoteItem->setCustomPrice($custom_price);
$quoteItem->setOriginalCustomPrice($custom_price);
$quoteItem->getProduct()->setIsSuperMode(true);
$quote->save();
We all know that a configurable product in magento is associated with simple product.
If the simple products associated to the configurable product becomes Inventory = 0, it means that the configurable product is out of stock
So the question is how do i detect if Configurable Product is out of stock? i want to detect so I can display in front-end the "Out of Stock" text.
something like this
if($configurable_product->isOutOfStock()) {
echo "Out of Stock";
}
How can i do this in Magento?
if (!$configurable->isSaleable() ||$configurable_product->getIsInStock()==0){
// out of stock
}
For checking child simple product:
$allProducts = $configurable->getTypeInstance(true)
->getUsedProducts(null, $configurable);
foreach ($allProducts as $product) {
if (!$product->isSaleable()|| $product->getIsInStock()==0) {
//out of stock for check child simple product
}
}
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter('type_id', array('eq' => 'configurable'));
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($_productCollection);
This shows only the configurable products that are in stock.
Just a slight update/correction to Quovadisqc's answer. When defining $qty it should be
$qty = $stockItem->getData('qty'); // correct
Instead of what's currently there,
$qty = $stockItem->setData('qty'); // incorrect
I'd post this as a comment but I don't have enough rep.
In the foreach loop of products the following if statement works.
if ($product->getIsInStock() === '1' && $product->isSaleable() === true) {
echo 'this product is in stock';
}
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
$qty = $stockItem->getData('qty');
$inStock = $stockItem->getData('is_in_stock');
if ($qty < 1 || $inStock == 0) {
// OutOfStock
}
I prefer to double check with qty since products won't always be out of stock on qty == 0 depending on config settings.
I know how to add products to a customer's wishlist programmatically however it only adds to one wishlist. I have the multiple wishlist option set to enabled however I do not know how to create a new wishlist instead of merging products into the existing wishlist.
public function submitQuote(Mage_Adminhtml_Model_Session_Quote $quote)
{
$currentQuote = $quote->getQuote();
$customer = $currentQuote->getCustomer();
$items = $currentQuote->getAllVisibleItems();
//$wishlist = Mage::helper('wishlist')->getWishlist();
//Mage::register('wishlist', $wishlist);
$wishlist = Mage::getModel('wishlist/wishlist');
$curretDate = date('m/d/Y', time());
$wishlist->setCustomerId($customer->getId());
$wishlist->setName('Quote ' . $curretDate)
->setVisibility(false)
->generateSharingCode()
->save();
foreach ($items as $item)
{
$productId = $item->getProductId();
$product = Mage::getModel('catalog/product')->load($productId);
$buyRequest = $item->getBuyRequest();
$result = $wishlist->addNewItem($product, $buyRequest);
if(is_string($result))
{
Mage::throwException($result);
}
$wishlist->save();
}
//Mage::unregister('wishlist');
}
I've had this problem before. To add a product to a customer's wishlist you need to start a wishlist model and call the addNewItem method passing the product object. Here is how I do it.
$customer = Mage::getModel('customer/customer');
$wishlist = Mage::getModel('wishlist/wishlist');
$product = Mage::getModel('catalog/product');
$customer_id = 1;
$product_id = 1;
$customer->load($customer_id);
$wishlist->loadByCustomer($customer_id);
$wishlist->addNewItem($product->load($product_id));
Hope this helps!
EDITED:
$customerid= "YOUR CUSTOMER ID "; // Modify This
$customer=Mage::getModel("customer/customer")->load($customerid);
$wishlist=Mage::getModel("wishlist/wishlist")->loadByCustomer($customer,true);
Check for reference this: app/code/core/Mage/Wishlist/Model/Wishlist.php
LATEST EDIT:
I see that your problem is here:
$result = $wishlist->addNewItem($product, $buyRequest);
FINAL EDIT:
Then create another function and add the items and wishlist you want to add it to (as parameters). This should add items to the wishlist that you have passed as an argument when calling the function. Its the only solution I can come up with. Hope this helps!
I just stumbled across this question because I'm trying to do something similar - your code part helped me to create a new wishlist, and I've managed to do the rest so thought I'd share.
This code will;
Create a new wishlist with the name 'Quote dd/mm/YY h:m:s'
Load the wishlist collection for the current user, ordered by highest ID first
Load the newest wishlist
Add all basket items to it
Redirect the user to the new wishlist view.
public function addToQuoteAction() {
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
$customerId = $customerData->getId();
} else {
Mage::getSingleton('core/session')->addError($this->__('Please login to use this feature'));
return $this->_redirectUrl($this->_getRefererUrl());
}
// Create the wishlist
$newWishlist = Mage::getModel('wishlist/wishlist');
$curretDate = date('d/m/Y h:m:s', time());
$newWishlist->setCustomerId($customerId);
$newWishlist->setName('Quote ' . $curretDate)
->setVisibility(false)
->generateSharingCode()
->save();
// Find the newly create list and load it
$wishlistCollection = Mage::getModel('wishlist/wishlist')->getCollection()
->addFieldToFilter('customer_id',$customerId)->setOrder('wishlist_id');;
$firstWish = $wishlistCollection->getFirstItem();
$wishlist = Mage::getModel('wishlist/wishlist')->load($firstWish->getWishlistId());
$cart = Mage::getModel('checkout/cart')->getQuote();
//getAllItems
foreach ($cart->getAllVisibleItems() as $item) {
$productId = $item->getProductId();
$buyRequest = $item->getBuyRequest();
$result = $wishlist->addNewItem($productId, $buyRequest);
$wishlist->save();
}
Mage::getSingleton('core/session')->addSuccess($this->__('All items have been moved to your quote'));
return $this->_redirectUrl(Mage::getBaseUrl().'wishlist/index/index/wishlist_id/'.$firstWish->getWishlistId().'/');
}
I have some product that has custom prices. Depending on the option selected, there is a formula applied that add fees to the product, so the price is never the same. The problem I have is that when you reorder, the price of the reordered product is always 0.
In sales/controllers/OrderController , in the function reorder,there is this :
$order = Mage::registry('current_order');
$items = $order->getItemsCollection();
foreach ($items as $item) {
try {
$cart->addOrderItem($item);
...
If I add these lines , I’m able to retrieve the custom price, but I can’t find a way to edit the item so that is the price being added in the reorder.
$options = $item->getProductOptions();
$options = $options['info_buyRequest'];
$customPrice = $options['custom_price'];
There is what I have tried (in the loop, before $cart->addOrderItem($item) ), without success.
$item->setSpecialPrice($customPrice);
$item->setCustomPrice($customPrice);
$item->setOriginalPrice($customPrice);
$item->setBaseOriginalPrice($customPrice);
$item->setBaseCost($customPrice);
$item->setBaseRowInvoiced($customPrice);
$item->setRowInvoiced($customPrice);
$item->save();
Any help?
Several possibilities. I'd try an event observer for the checkout_cart_product_add_after event.
// observer method:
public function checkoutCartProductAddAfter(Varien_Event_Observer $observer)
{
$action = Mage::app()->getFrontController()->getAction();
if ($action->getFullActionName() == 'sales_order_reorder')
{
$buyInfo = $observer->getQuoteItem()->getBuyRequest();
if ($customPrice = $buyInfo->getCustomPrice())
{
$observer->getQuoteItem()->setCustomPrice($customPrice)
->setOriginalCustomPrice($customPrice);
}
}
}
I'm working on a script that will create or update products in my catalog.
The script works fine when the product needs to be created, but it fails when the product already exists in the database giving me (many times) the following messages :
2011-09-30T08:00:53+00:00 ERR (3): Recoverable Error: Argument 3
passed to
Mage_Catalog_Model_Resource_Eav_Mysql4_Abstract::_canUpdateAttribute()
must be an array, null given, called in ...
2011-09-30T08:00:53+00:00
ERR (3): Recoverable Error: Argument 3 passed to
Mage_Eav_Model_Entity_Abstract::_canUpdateAttribute() must be an
array, null given, called in ...
2011-09-30T08:00:53+00:00 ERR (3):
Warning: array_key_exists() [function.array-key-exists]: The
second argument should be either an array or an object in ...
I've been looking at the method quoted in the message, but I can't find any reason why the script fails.
The script first try to load a product using :
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
and then test if the product was retrieved using a simple if(!$product) { //creation }.
All the code that follow the if statement is shared for creation or update and consists of setter calls on product object.
Here is the code I use :
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
if(!$product) {
// the product doesn't exist yet
$product = new Mage_Catalog_Model_Product();
$product->setSku($sku);
$product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE);
$product->setCreatedAt(strtotime('now'));
}
// setters calls
$product->setTeinte(trim((string)$record->web_teinte));
// ...
// finally save the product
$product->save();
Maybe someone has already faced the same problem.
Any help is welcome ! Thank you.
Chances are, in your "setter calls" you are trying to set something that cannot be directly set on $product. It could even be the "setTeinte" as I am not sure what that is trying to set. But as we cannot see all your code, it is a little difficult to say, so as I guide, take a look at the code below, which sets some information directly on the product and then stock levels. It does therefore, illustrate how certain data has to be set. I hope it helps.
$SKU = (string)$XMLproduct->Sku;
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$SKU);
if ($product) {
//Product found, so we need to update it in Magento.
$product->setName((string)$XMLproduct->Name);
$product->setPrice((real)$XMLproduct->SalePrice);
//$product->setDescription((string)$XMLproduct->LongDescription);
//$product->setShortDescription((string)$XMLproduct->Description);
$product->save();
$productId = $product->getId();
$stockItem =Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockItemId = $stockItem->getId();
$stockItem->setData('manage_stock', 1);
$stockItem->setData('qty', (integer)$XMLproduct->QtyInStock);
$stockItem->save();
echo $SKU," Updated: Name: '",(string)$XMLproduct->Name,"', Price: ",(real)$XMLproduct->SalePrice,", Stock level: ",$XMLproduct->QtyInStock,PHP_EOL;
$updated++;
}
Adding Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); before saving product solves the error. The sample code below updates product's cost.
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$productId = 160;
$newCost = 80;
$product = Mage::getModel('catalog/product')->load($productId);
$product->setCost($newCost)->save();
//here what i use in codeigniter
function updateProducts(){
$params = array('name' => 'adminhtml'); // frontend or adminhtml
$this->load->library('magento', $params);
error_reporting(E_ALL | E_STRICT);
//$mageFilename = 'app/Mage.php';
//require_once $mageFilename;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$obj = new stdClass();
$obj->Sku = '25484684';
$obj->Name = 'test product 2';
$obj->SalePrice = 55;
$obj->LongDescription = 'test product long decription.test product long decription.test product long decription.';
$obj->Description = 'short descrption';
$res = $this->updateMagentoProduct($obj);
//dumb($res);
}
function updateMagentoProduct($XMLproduct){
$SKU = (string)$XMLproduct->Sku;
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$SKU);
if (!$product) {//insert new product
$product = Mage::getModel('catalog/product');
$product->setSku($SKU);
}
//$product = new Mage_Catalog_Model_Product();
// Build the product
$product->setAttributeSetId(4); // 4 means Default AttributeSet
$product->setTypeId('simple');
$product->setName((string)$XMLproduct->Name);
$product->setCategoryIds(array(2,3,4,5,6,7));
$product->setWebsiteIDs(array(1)); # Website id, 1 is default
//$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
//$product->setWebsiteIDs(array(1)); # Website id, my is 1 (default frontend)
$product->setDescription((string)$XMLproduct->LongDescription);
$product->setShortDescription((string)$XMLproduct->Description);
$product->setPrice((real)$XMLproduct->SalePrice);
# Custom created and assigned attributes
//$product->setHeight('my_custom_attribute1_val');
//$product->setWidth('my_custom_attribute2_val');
//$product->setDepth('my_custom_attribute3_val');
//$product->setType('my_custom_attribute4_val');
//Default Magento attribute
$product->setWeight(1.0);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setStatus(1);
$product->setTaxClassId(0); # My default tax class
/*$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));*/
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
$productId = $product->getId();
$stockItem =Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockItemId = $stockItem->getId();
$stockItem->setData('manage_stock', 1);
$stockItem->setData('qty', 99999);//(integer)$XMLproduct->QtyInStock
$stockItem->save();
echo '<h5>'.$SKU," Updated: Name: '",(string)$XMLproduct->Name,"', Price: ",(real)$XMLproduct->SalePrice,", Stock level: ",PHP_EOL.'</h5>';
}
catch (Exception $ex) {
//Handle the error
echo '<h5>'.$ex->getMessage().'</h5>';
}
// assign product to the default website
return $product->save();
}
Easy with Magento API,
also can use methods....
example
$data = array('qty'=>1, 'is_in_stock'=>1)
$stockModel = new Mage_CatalogInventory_Model_Stock_Item_Api;
$stockModel->update($product_id, $data);
Also can set Admin mode
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
<?php
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
$product
// ->setStoreId(1) //you can set data in store scope
->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
->setAttributeSetId(9) //ID of a attribute set named 'default'
->setTypeId('simple') //product type
->setCreatedAt(strtotime('now')) //product creation time
// ->setUpdatedAt(strtotime('now')) //product update time
->setSku('testsku61') //SKU
->setName('test product21') //product name
->setWeight(4.0000)
->setStatus(1) //product status (1 - enabled, 2 - disabled)
->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
->setManufacturer(28) //manufacturer id
->setColor(24)
->setNewsFromDate('06/26/2014') //product set as new from
->setNewsToDate('06/30/2014') //product set as new to
->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
->setPrice(11.22) //price in form 11.22
->setCost(22.33) //price in form 11.22
->setSpecialPrice(00.44) //special price in form 11.22
->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
->setMsrpEnabled(1) //enable MAP
->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
->setMsrp(99.99) //Manufacturer's Suggested Retail Price
->setMetaTitle('test meta title 2')
->setMetaKeyword('test meta keyword 2')
->setMetaDescription('test meta description 2')
->setDescription('This is a long description')
->setShortDescription('This is a short description')
->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
->addImageToMediaGallery('media/catalog/product/1/0/10243-1.png', array('image','thumbnail','small_image'), false, false) //assigning image, thumb and small image to media gallery
->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock'=>1, //manage stock
'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 999 //qty
)
)
->setCategoryIds(array(3, 10)); //assign product to categories
$product->save();