MAGENTO - Load last created Product to Cart - magento

is it possible to load the last registered (created) Product in my Cart?
How?
I know it sounds crazy but i need this for one of my project.
I think this is the part where the Product gets loaded:
cartcontroller.php
/**
* Initialize product instance from request data
*
* #return Mage_Catalog_Model_Product || false
*/
protected function _initProduct()
{
$productId = (int) $this->getRequest()->getParam('product');
if ($productId) {
$product = Mage::getSingelton('checkout/session')->getQuote()->getAllItems()
->setStoreId(Mage::app()->getStore()->getId())
->load($productId);
if ($product->getId()) {
return $product;
}
}
return false;
}
This (if I´m right) i need to be replaced with the last in shop created Product - sound weired but i need this....

You're almost there - try this code:
$collection = Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection();
$collection->getSelect()->order('created_at DESC');
$latestItem = $collection->getLastItem();
Note that when you get the latest quote item, you're not actually obtaining the product. To get the actual product, you would need to add this line:
$product = $latestItem->getProduct();

You can get the items in the cart like this:
$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
Then loop through the items and see which one has the biggest id.
$max = 0;
$lastItem = null;
foreach ($items as $item){
if ($item->getId() > $max) {
$max = $item->getId();
$lastItem = $item;
}
}
if ($lastItem){
//do something with $lastItem
}

Related

Laravel session

I have done projects laravel shopping cart when clicking on the product detail page will open and click the add to cart sends the id to CartController # index. I then access the database and retrieve product information and I put on the session. Then I bought other products but my older products lost in session when I turn the page. Who can help me thanks
Probably you don't add this to existed array in session, but replace it.
Should do it this way:
$products = Session::get('products', array()); // get existed products or empty array
$products[] = $newProduct; // add new product to list
Session::put('products', $products); // put all products to session
this is my code for cart
public function addItem($ids,Request $request){
$data = Product::find($ids)->toArray();
$name =$data['name'];
$price = $data['price'];
$cart = $request->session()->get('cart');
if($cart==null){
$cart['quantity'][$ids] = 1;
$cart['price'][$ids] = $price;
$cart['name'][$ids] = $name;
$request->session()->put('cart', $cart);
}else{
if(array_key_exists($ids,$cart['quantity'])){
$cart['quantity'][$ids] += 1;
$cart['price'][$ids] = $price * $cart['quantity'][$ids];
$cart['name'][$ids] = $name;
}else{
$cart['quantity'][$ids] = 1;
$cart['price'][$ids] = $price;
$cart['name'][$ids] = $name;
}
$request->session()->put('cart', $cart);
}
}

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 Simple Product from Configurable in Cart

I'm trying to load the simple products that have been added to a customer's cart, but when I retrieve the items, it's showing the parent configurable.
$cart = Mage::getSingleton('checkout/cart');
$productIds = array();
foreach ($cart->getQuote()->getAllVisibleItems() as $item) {
$productIds[] = $item->getProduct()->getId();
}
var_dump($productIds);
For instance, this will return all the same configurable id when I've added a small, medium, and large to my cart. How can I get the individual simple products? I'm trying to retrieve an attribute value that's set on the simple product level.
After taking a look at how Magento renders the items in your cart on the checkout/cart page, I was able to find this in app/code/core/Mage/Checkout/Block/Cart/Item/Renderer/Configurable.php
/**
* Get item configurable child product
*
* #return Mage_Catalog_Model_Product
*/
public function getChildProduct()
{
if ($option = $this->getItem()->getOptionByCode('simple_product')) {
return $option->getProduct();
}
return $this->getProduct();
}
So, applying it to the snippet in the question, it would be
foreach ($cart->getQuote()->getAllVisibleItems() as $item) {
$productId = $item->getProduct()->getId();
if ($option = $item->getOptionByCode('simple_product')) {
$productId = $option->getProduct()->getId();
}
$productIds[] = $productId;
}

In Magento how do I get the listing of categories in the order you see in the admin area?

I can get a list of the children categories for a specific category with the following code:
public function displaycats($data, $begin,$end, $catid){
$currentCat = Mage::getModel('catalog/category')->load($data[0]);
$children = explode(",",$currentCat->getChildren());
foreach ($children as $child) {
$cot++;
$subCat = Mage::getModel('catalog/category')->load($child);
if ($cot >= $begin && $cot <= $end){
echo ''.$subCat->getName()."<br>";
}
}
return;
}
The problem is that the list is not ordered the same as Magento has the categories ordered in the admin area. Can anyone help me out?
I like #Joe Constant's answer, but when I tried it, I was having trouble only getting the first level of child categories, even with $recursionLevel set to 0. As a workaround, I wrote this function (place it in (local version of) whichever block you need the sorted child collection):
public function getChildrenCollection($parentId=false, $sort='ASC', $attribute='position')
{
if (empty($parentId) || !is_numeric($parentId)) return false;
$childrenArray = explode(',',Mage::getModel('catalog/category')->load($parentId)->getChildren());
// remove parent id from array in case it gets returned
if ($key = array_search($parentId, $childrenArray)) {
unset($childrenArray[$key]);
}
$collection = Mage::getModel('catalog/category')->getCollection()
->addAttributeToFilter('entity_id', array('in' => $childrenArray))
->addAttributeToSelect('*');
if (!empty($sort)) {
return $collection->setOrder($attribute, $sort);
}
return $collection;
}
Then you can iterate through the collection and do whatever you need like this:
foreach (getChildrenCollection($parentCategoryId) as $child) {
Zend_Debug::dump($child->getData());
}
Hope that helps.
Look at getCategories instead. It has a sorted parameter as well as an option to return as a collection object removing the need to load each category from the database again.
/**
* Retrieve categories
*
* #param integer $parent
* #param integer $recursionLevel
* #param boolean|string $sorted
* #param boolean $asCollection
* #param boolean $toLoad
* #return Varien_Data_Tree_Node_Collection|Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection
*/
public function getCategories($parent, $recursionLevel = 0, $sorted=false, $asCollection=false, $toLoad=true)
`
$helper = Mage::helper('catalog/category');
$_categories = $helper->getStoreCategories('path', true, FALSE);
If you want to display the category in the following format
category 1
--- sub category 1a
------ sub category 1aa
--- sub category 1b
category 2
---sub category 2a
---sub category 2b
foreach($_categories as $category){
$level = $category['level'] - 2;
$pad = str_repeat("---", ($level > 0) ? $level : 0);
echo $pad . ' ' . $cat['name']);
echo '<br/>';
}
return $categories;
I just wrote something like this to get list of categories (by parentId) sorted like in admin:
$subCats = array();
$children = Mage::getModel('catalog/category')->getCategories($parentId, 1, true, true);
foreach ($children as $category)
{
$subCats[$category->getPosition()] = $category->getId();
}
ksort($subCats);

Check whether a product is in the wishlist or not

I'm working on a Magento theme, and I need to build a function that can check to see whether or not a product has been added to the user's wishlist.
Magento has a "Mage_Wishlist_Helper_Data" helper class, but I have no idea how to build a check-if-already-in-wishlist function. Basically I need to use Magento's wishlist feature to build a favorites list. I want to add a special class to the "add to wishlist" link if the particular product was already added to the user's favorites.
<?php $wishlist = Mage::getModel('wishlist/item')->load($_product->getId(),'product_id');
if($wishlist->getId())
//product is added
echo "Added! - Product is in the wishlist!";
else
//add product to wishlist
echo "<a href='".$this->helper('wishlist')->getAddUrl($_product) ."'>Add This?</a>";
;?>
Since collections are lazy loaded, I am assuming you can do something such as:
$_product = ...; // some product object you already have
$_productCollection = Mage::helper('wishlist')->getProductCollection()
->addFieldToFilter('sku', $_product->getSku());
if($_productCollection->count() > 0) {
// User already has item in wishlist.
}
You can do similar filtering on other fields, but SKU should be sufficient in this case.
I'm only getting back to this project now, but I took Daniel Sloof's suggestion, and it worked perfectly using the function below:
public function isInWishlist($item)
{
$_productCollection = Mage::helper('wishlist')->getProductCollection()
->addFieldToFilter('sku', $item->getSku());
if($_productCollection->count()) {
return true;
}
return false;
}
This checks to see whether or not a product has been added into the current user's Wishlist. I called it my template file like this:
if ($this->helper('wishlist')->isInWishlist($_product)) :
I found this solution after checked select query of Mage::helper('wishlist')->getWishlistItemCollection(). I hope this solution help to someone.
/**
* Check customers wishlist on identity product.
* #param Mage_Catalog_Model_Product $_product
* #return bool
*/
private function _isInWishlist($_product)
{
$_productCollection = Mage::helper('wishlist')->getWishlistItemCollection()
->addFieldToFilter('product_id', $_product->getId());
if ($_productCollection->count()) {
return true;
}
return false;
}
I solved this by the below function. I Hope this may help some one.
function checkInWishilist($_product){
Mage::getSingleton('customer/session')->isLoggedIn();
$session = Mage::getSingleton('customer/session');
$cidData = $session->isLoggedIn();
$customer_id = $session->getId();
if($customer_id){
$wishlist = Mage::getModel('wishlist/item')->getCollection();
$wishlist->getSelect()
->join(array('t2' => 'wishlist'),
'main_table.wishlist_id = t2.wishlist_id',
array('wishlist_id','customer_id'))
->where('main_table.product_id = '.$_product->getId().' AND t2.customer_id='.$customer_id);
$count = $wishlist->count();
$wishlist = Mage::getModel('wishlist/item')->getCollection();
}
else {
$count="0";
}
if ($count) :
return true;
else:
return false;
endif;
}
Since #alexadr.parhomenk s' solution causes undesired results, here's a smaller method that does the trick:
/**
* Check customers wishlist on identity product.
* #param int $productId
* #return bool
*/
public function isInWishlist($productId)
{
$ids = Mage::registry('wishlist_ids');
if (!$ids) {
$productCollection = Mage::helper('wishlist')->getWishlistItemCollection();
$ids = $productCollection->getColumnValues('product_id');
Mage::register('wishlist_ids', $ids);
}
return in_array($productId, $ids);
}

Resources