I try to add a extra product to the cart. I have created a observer for this.
<?php
class WP_Plugadapter_Model_Observer
{
public function hookToControllerActionPostDispatch($observer)
{
if($observer->getEvent()->getControllerAction()->getFullActionName() == 'checkout_cart_add')
{
Mage::dispatchEvent("add_to_cart_after", array('request' => $observer->getControllerAction()->getRequest()));
}
}
public function hookToAddToCartAfter($observer)
{
$request = $observer->getEvent()->getRequest()->getParams();
$_product = Mage::getModel('catalog/product')->load($request['product']);
$extra_functions = $_product->getExtra_functions();
if(!empty($extra_functions)){
$extra_functions = explode(',', $extra_functions);
if(array_search('121', $extra_functions)){
$cart = Mage::getSingleton('checkout/cart');
$cart->addProduct(10934, 1);
$cart->save();
if (!$cart->getQuote()->getHasError()){
Mage::log("Product ADD TO CART is added to cart.");
}else{
Mage::log("BOEM");
}
}
}
}
}
When i check mine system log i see the following log message. Product ADD TO CART is added to cart.
I have no clue what i'm doing wrong. When a load the script standalone it's working fine.
For example:
<?php
include_once '../app/Mage.php';
Mage::app();
umask(0);
$session = Mage::getSingleton('core/session', array('name'=>'frontend'));
$cart = Mage::getSingleton('checkout/cart');
$cart->addProduct(10934, 1);
$cart->save();
Is it possible that in a observer you have it to do it in a different way?
The problem is that cart's quote object is not saved to the database and later in the request processing is overwritten by the quote object from the session. Why the cart quote is not saved is quite confusing. The save method of the quote model expects that the internal property _hasDataChanges is set to true. This property is, however, remains at false, even though a product was added to the quote.
You can force that property to be set to true by adding some data (any property would do) to the quote using the setData method:
$cart = Mage::getSingleton('checkout/cart');
$cart->addProduct(10934, 1);
//force _hasDataChanges to true
$cart->getQuote()->setData('updated', true);
$cart->save();
Alternatively you can use the checkout session quote object to add a product to the cart
if(array_search('121', $extra_functions)){
$cart = Mage::getSingleton('checkout/cart');
$qty = 1;
$quote = Mage::getSingleton('checkout/session')->getQuote()
->addProduct(
Mage::getModel('catalog/product')->load(10934),
$qty)
->save();
$cart->save();
if (!$cart->getQuote()->getHasError()){
Mage::log("Product ADD TO CART is added to cart.");
}else{
Mage::log("BOEM");
}
}
Related
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);
}
}
I want to get list of products which belongs to the selected manufacturer on custom module's frontend. I successfully got the list of manufacturers but I can't retrieve the products related to particular manufacturer. I searched it a lot but I didn't got any solution.
Here is my code
block file:-
public function __construct()
{
parent::__construct();
$brand_id = $this->getRequest()->getParam('id');
$layer = $this->getLayer();
//$collection = Mage::getModel('catalog/product')->getCollection()
$collection = $layer->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('manufacturer', 20);
$this->setCollection($collection);
}
public function getProductCollection()
{
if (is_null($this->_productCollection))
{
$layer = $this->getLayer();
//$collection = Mage::getModel('catalog/product')->getCollection()
$collection = $layer->getProductCollection()
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addAttributeToFilter('manufacturer', 20)
->addStoreFilter(Mage::app()->getStore()->getId())
->addMinimalPrice()
->addUrlRewrite();
$this->_productCollection = $collection;
Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($this->_productCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($this->_productCollection);
}
return $this->_productCollection;
}
public function getColumnCount()
{
return 3;
}
and this is my phtml code
<?php
$product = $this->getProductCollection();
foreach ($product as $prods)
{
echo '<pre>'; print_r($prods->getData()); die;
}
?>
As mentioned above you will need to follow a few steps:
1) Goto Attribute Sets, and make sure "manufacturer" is assigned to the attribute set you are using.
2) Make sure you have added some manufacturers into the attribute options.
3) Assign one of the options to your product.
Depending on your magento version this should work:
<?php echo $_product->getAttributeText('manufacturer') ?>
I can see the error you are getting:
gives error Call to a member function getManufacturer() on a non-object in
Are you sure you are putting this code after this line:
<?php $_product = $this->getProduct(); ?>
Hope this solutions have make you day ....!!!
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 need to generate shipping label dynamically once order is placed.
I have fedex shipping method configured and works fine for setting the order status to shipping once order placed and from admin am able to create shipping label manually and it is giving pdf when i click Print Shipping label after shipping label created.
Now this process needs to be automated - how i can able to create hipping labels dynamically? Is there any observer or class overwriting examples. Please help me to create shipping label dynamically
If you want an official Shipping Label with bar code you will need to purchase an extension like this one:
http://www.cobbconsulting.net/magento-fedex-extension.html
The extension has a cahcing feature where it will store all of your shipping labels so you can easily re-print them at anytime.
As know, you can print shipping label only when have invoice. We want let you know extension can help you solved. Or you can check our code for create
Magento 1: http://www.mlx-store.com/magento-extensions/shipping/print-shipping-label.html
Magento 2: http://www.mlx-store.com/magento2-extensions/shipping/print-shipping-label-for-magento-2.html
or use code
Below is the controller.
public function printShippingLabelAction(){
$ids= $this->getRequest()->getPost('order_ids');
if (!empty($invoicesIds)) {
$orders = Mage::getResourceModel('sales/order')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', array('in' => $ids))
->load();
if (!isset($pdf)){
$pdf = Mage::getModel('sales/order_pdf_order')->getPdf($orders );
} else {
$pages = Mage::getModel('sales/order_pdf_order')->getPdf($orders );
$pdf->pages = array_merge ($pdf->pages, $pages->pages);
}
return $this->_prepareDownloadResponse('order'.Mage::getSingleton('core/date')->date('Y-m-d_H-i-s').
'.pdf', $pdf->render(), 'application/pdf');
}
$this->_redirect('*/*/');
}
Create model
class Mage_Sales_Model_Order_Pdf_Order extends Mage_Sales_Model_Order_Pdf_Invoice
{
public function getPdf($orders = array())
{
$this->_beforeGetPdf();
$this->_initRenderer('order');
$pdf = new Zend_Pdf();
$this->_setPdf($pdf);
$style = new Zend_Pdf_Style();
$this->_setFontBold($style, 10);
foreach ($orders as $order) {
$page = $this->newPage();
$this->insertLogo($page, $order->getStore());
$this->insertAddress($page, $order->getStore());
$this->insertOrder(
$page,
$order,
Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID, $order->getStoreId())
);
$this->insertDocumentNumber(
$page,
Mage::helper('sales')->__('Order # ') . $order->getIncrementId()
);
$this->_drawHeader($page);
foreach ($order->getAllItems() as $item){
if ($item->getOrderItem()->getParentItem()) {
continue;
}
$this->_drawItem($item, $page, $order);
$page = end($pdf->pages);
}
$this->insertTotals($page, $order);
if ($order->getStoreId()) {
Mage::app()->getLocale()->revert();
}
}
$this->_afterGetPdf();
return $pdf;
}}
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);
}