Check If Product Exists - magento

I have some php code which I use SKU for it:
$sku = $id
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();
What I would like to add to this code if $sku is wrong (Not found in database with $_product line) to be able to change it manually for example if the $sku is not existent change it to $sku = "909010";
Thank you for the help

function get_product($sku){
$product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
if (!$product){
$new_sku = '909010'; // If Real SKU doesn`t exsist, change to '909010'
$product=Mage::getModel('catalog/product')->loadByAttribute('sku',$new_sku);
}
return $product;
}
var_dump(get_product('your-sku')); // Real Sku

$sku = $id
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
if(!is_object($_product) || !$_product->getId()){
//do your stuff here
}
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();

$sku = $id
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
$_product = !empty($product) ? $product : Mage::getModel('catalog/product')->loadByAttribute('sku','YOUR-ERROR-SKU');
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();

Related

Magento Multiple Wishlist creation programmatically

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().'/');
}

get qty of products in an order with several products

Hi i would like to know how to get the qty_ordered of a specific product in an order with several products.
i have tried these
$orders = Mage::getModel('sales/order')->getCollection()->
addAttributeToSelect('shipping_description')->
addAttributeToSelect('increment_id')->
addAttributeToSelect('base_grand_total')->
addAttributeToSelect('total_qty_ordered')->
addAttributeToSelect('shipping_address_id')->
addAttributeToSelect('billing_address_id')->
addAttributeToSelect('created_at')->
addAttributeToSelect('shipping_incl_tax')->
addAttributeToFilter('status', 'pending');
but addAttributeToSelect('total_qty_ordered')-> which total? which product?
"total_qty_ordered" give total no orders qty of all product in an order
If,you want item qty of product then
you can try
<?php $order_id = 2314; //use your own order id
$order = Mage::getModel("sales/order")->load($order_id); //load order by order id
$ordered_items = $order->getAllItems();
foreach($ordered_items as $item){ //item detail
echo $item->getItemId();
//product id
echo $item->getSku();
echo $item->getQtyOrdered();
//ordered qty of item
echo $item->getName();
// etc.
} ?>
for me it worked like this:
<?php
$_order = $this->getOrder(); //call the order
$order_qty = floor($_order->getData('total_qty_ordered')); //get qty of all items rounded to full number (without 3.0000 or so)
echo $order_qty;
?>
used it on template/sales/order/totals.phtml
You can Try this also:-
$orderCollection = Mage::getModel('sales/order');
$order_data = $orderCollection->getAllVisibleItems();
foreach ($order_data as $key) {
$id = $key->getProductId();
$orderItems = Mage::getResourceModel('sales/order_item_collection')
->addAttributeToFilter('product_id', $id);
foreach ($orderItems as $key ) {
echo $number_of_prod = $key->getQtyOrdered();
}
}

How to show price range of custom option in magento

I am using magento 1.7, on the product detail price I have some custom option and some configurable product option.
What I want to do is that I want to show the price of the all the option in range, like if lowest total price option is 18.50 and highest total price option is 55.90 than it should show somewhere on product page like "18.50 - 55.90".
Thanks in advance.
try below code
//load configurable product
$product = Mage::getModel('catalog/product')->load(some_id);
//load all children
$childProducts = Mage::getModel('catalog/product_type_configurable')
->getUsedProducts(null,$product);
foreach($childProducts as $child){
$_child = Mage::getModel('catalog/product')->load($child->getId());
$childPrice = $_child->getPrice();
//compare the $childPrice
}
or for inline query should be like
<?php
$db = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $db->query('SELECT a.product_id, a.product_super_attribute_id, ap.product_super_attribute_id, ap.pricing_value FROM catalog_product_super_attribute AS a INNER JOIN catalog_product_super_attribute_pricing AS ap ON a.product_super_attribute_id=ap.product_super_attribute_id WHERE a.product_id='.$_product->getId().' ORDER BY ap.pricing_value DESC LIMIT 1');
$rows = $result->fetch();
echo 'From '.Mage::helper('core')->currency($_product->getPrice()).' to '.Mage::helper('core')->currency($rows ['pricing_value']+$_product->getPrice());
?>
Edit (optional)
$prices = array();
$associated = $_product->getTypeInstance(true)->getAssociatedProductCollection($_product)
->addAttributeToSelect('special_pric$
foreach ($associated as $assoc) {
$prices[] = $assoc->getSpecialPrice();
}
if (count($prices)) {
$min_price = min($prices);
$max_price = max($prices);
} else {
$min_price = 0;
$max_price = 0;
}

Get Random SKU Product Number

I have the following code:
$sku = $id;
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();
It works by specfing the SKU id, I want to be able to get random SKU product number and use it so
$sku = random product number from database
I used the following script to generate a random sku from the collection. You can use it to suit your requirement also.
//Geting a random sku from collection
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$randomSku = $collection->setPage(1, 1)->getFirstItem()->getSKU();
In your case your code should look like.......
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$_product = $collection->setPage(1, 1)->getFirstItem()->load();
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();
Something like that should work fine ;)
$collection = Mage::getResourceModel(‘catalog/product_collection’);
Mage::getModel(‘catalog/layer’)->prepareProductCollection($collection);
$collection->getSelect()->order(‘rand()’);
$collection->addStoreFilter();
$collection->setPage(1, 1);
$_product = $collection->getFirstItem();
Below code I used in project and its working fine for me :
<?php
// get Random prdocut list
$collection = Mage::getResourceModel(‘catalog/product_collection’);
Mage::getModel(‘catalog/layer’)->prepareProductCollection($collection);
$collection->getSelect()->order(‘rand()’);
$collection->addStoreFilter();
$numProducts = $this->getNumProducts() ? $this->getNumProducts() : 2;
$collection->setPage(1, $numProducts);
foreach($collection as $product){
echo $product->getName();
}
?>

Magento - Product Collection with the current user's Wishlist

Within a Magento php Controller, how can I get a Product Collection containing the products listed in the logged in user's (ie current user's) Wishlist.
I am getting the Wishlist using:
$wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer(Mage::getSingleton('customer/session')->getCustomer());
and this contains the correct number of items.
But I would like to get a Product Collection. I have tried:
$productCollection = $wishList->getProductCollection();
and
$productCollection = $wishList->getProductCollection()->addAttributeToSelect('id')->load();
but the Product Collection I get has a length of 0.
How do I get the Product Collection?
You can use the getWishlistItemCollection (see link for more details) off the wishlist helper to return a collection of items, you then need to get the product from the item.
I have been using the following code to create an associative array of the products, which I then use to determine if a product I am displaying in the list page is in the wishlist...hopefully this will help:
public function getWishList() {
$_itemCollection = Mage::helper('wishlist')->getWishlistItemCollection();
$_itemsInWishList = array();
foreach ($_itemCollection as $_item) {
$_product = $_item->getProduct();
$_itemsInWishList[$_product->getId()] = $_item;
}
return $_itemsInWishList;
}
Try this with product all details like name, images etc...
<?php
$customer = Mage::getSingleton('customer/session')->getCustomer();
if($customer->getId())
{
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $item)
{
echo $item->getName()."</br>";
echo $item->getId()."</br>";
echo $item->getPrice()."</br>";
echo $item->getQty()."</br>";
$item = Mage::getModel('catalog/product')->setStoreId($item->getStoreId())->load($item->getProductId());
if ($item->getId()) :
?>
<img src="<?php echo Mage::helper('catalog/image')->init($item, 'small_image')->resize(113, 113); ?>" width="113" height="113" />
<?php endif; } } ?>
$customer = Mage::getSingleton('customer/session')->getCustomer();
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $item)
{
// do things
}

Resources