I get a request from an extrenal site containing some product ids.
In my module i try to load the products and add them to the shopping cart. I tried it with this code:
public function indexAction() {
$ids = explode(',', $this->getRequest()->getParam('products'));
Mage::log('ADDING PRODUCTS');
$cart = Mage::getModel('checkout/cart');
$cart->init();
$pModel = Mage::getSingleton('catalog/product');
//$cart->addProductsByIDs($ids);
foreach ($ids as $id) {
Mage::log('Loading: ' . $id);
$product = $pModel->load($id);
Mage::log('Loaded: ' . $product->getId());
try {
$cart->addProduct($product, array('qty' => '1'));
} catch (Exception $e) {
Mage::log($e);
continue;
}
}
$cart->save();
if ($this->getRequest()->isXmlHttpRequest()) {
exit('1');
}
$this->_redirect('checkout/cart');
}
I can see in the system.log that it loads the products correctly. But after the redirect i have the second product in my cart twice. The first one is missing. Using $cart->addProductsByIDs($ids) works great but then i cant influence the quantity of the products anymore.
Does someone know what i am doing wrong and give me a hint?
Thx
I had the same problem and I fixed it by loading the product model inside every loop:
public function AddMultipleItemsAction() {
$products = explode(',', $this->getRequest()->getParam('products'));
$quantities = explode(',', $this->getRequest()->getParam('quantities'));
$numProducts = count($products);
$cart = $this->_getCart();
for($i=0;$i<$numProducts;$i++) {
$product_id = $products[$i];
$quantity = $quantities[$i];
if ($product_id == '') continue;
if(!is_numeric($quantity) || $quantity <= 0) continue;
$pModel = Mage::getModel('catalog/product')->load($product_id);
if($pModel->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE) {
try {
$eventArgs = array(
'product' => $pModel,
'qty' => $quantity,
'additional_ids' => array(),
'request' => $this->getRequest(),
'response' => $this->getResponse(),
);
Mage::dispatchEvent('checkout_cart_before_add', $eventArgs);
$cart->addProduct($pModel, array('product'=>$product_id,'qty' => $quantity));
Mage::dispatchEvent('checkout_cart_after_add', $eventArgs);
Mage::dispatchEvent('checkout_cart_add_product', array('product'=>$pModel));
$message = $this->__('%s was successfully added to your shopping cart.', $pModel->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
} catch (Mage_Core_Exception $e) {
if (Mage::getSingleton('checkout/session')->getUseNotice(true)) {
Mage::getSingleton('checkout/session')->addNotice($pModel->getName() . ': ' . $e->getMessage());
}
else {
Mage::getSingleton('checkout/session')->addError($pModel->getName() . ': ' . $e->getMessage());
}
} catch (Exception $e) {
Mage::getSingleton('checkout/session')->addException($e, $this->__('Can not add item to shopping cart'));
}
}
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
$this->_redirect('checkout/cart');
}
I then have an "Add all items to cart" button which executes the following Javascript code:
<script type="text/javascript">
function addAllItemsToCart() {
productsArr = new Array();
quantitiesArr = new Array();
$$('#product-listing-table .qty').each(
function (input, index) {
productsArr[index] = encodeURIComponent(input.readAttribute('product_id'));
quantitiesArr[index] = encodeURIComponent(input.value);
}
);
var url = '/MyModule/Cart/AddMultipleItems/products/'+productsArr.join(',')+'/quantities/'+quantitiesArr.join(',')+'/';
setLocation(url);
}
For this to be able to work, I put an extra product_id attribute on the quantity textbox, such as:
<input type="text" size="2" product_id="<?php echo $_product->getId();?>" name="productqty_<?php echo $_product->getId();?>" class="qty" />
and the whole list of products is inside a div with ID product-listing-table
Just checked with some custom add to cart code that I've got, and confirmed is working correctly, and the only difference I have is:
$cart->addProduct($product, array(
'qty' => 1,
'product' => $product->getId(),
'uenc' => Mage::helper('core')->urlEncode(Mage::helper('core/url')->getCurrentUrl())
));
// Also make sure we know that the cart was updated
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
That said, your error doesn't make it sound like you're actually having trouble in this area. I can't imagine it would be this, but is it possible that the cart model needs to be save()d every time you add a product to the cart? It's worth a punt.
Related
I'm creating custom functions for sign up and adding product to customer cart.
If user signed up using my function first product that he/she added will not be added to the cart unless he added another product after that everything working perfect and the first product also appear in the cart.
If user signed up by using magento sign up form then used my function to add product to the cart everything working.
Sign up code
public function signupAction() {
$email = $this->getRequest()->getPost('email');
$password = $this->getRequest()->getPost('password');
$firstName = $this->getRequest()->getPost('firstName');
$LastName = $this->getRequest()->getPost('LastName');
$session = Mage::getSingleton('customer/session');
$session->setEscapeMessages(true);
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($firstName)
->setLastname($LastName)
->setEmail($email)
->setPassword($password);
try {
$customer->cleanPasswordsValidationData();
$customer->save();
$this->_dispatchRegisterSuccess($customer);
$this->_successProcessRegistration($customer);
} catch (Mage_Core_Exception $e) {
} catch (Exception $e) {
}
}
Add to cart code
public function addAction() {
$form_key = Mage::getSingleton('core/session')->getFormKey();
$json = $this->getRequest()->getPost('json');
$jsonObj = json_decode($json);
$cart = $this->_getCart();
$cart->init();
$response = array();
try {
foreach ($jsonObj as $data) {
$param = ['form_key' => $form_key,
'qty' => $data->qty, 'product' => $data->productId];
$product = $this->_initProduct($param['product']);
if ($data->type == 'simple') {
$cart->addProduct($product, $param);
}
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true)
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product,
'request' => $this->getRequest(),
'response' => $this->getResponse()));
if (!$cart->getQuote()->getHasError()) {
$response['status'] = 'SUCCESS';
} else {
$response['status'] = 'Error';
}
} catch (Mage_Core_Exception $e) {
$msg = "";
if ($this->_getSession()->getUseNotice(true)) {
$msg = $e->getMessage();
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$msg .= $message . '<br/>';
}
}
$response['status'] = 'ERROR';
$response['message'] = $msg;
} catch (Exception $e) {
$response['status'] = 'ERROR';
$response['message'] = $this->__('Cannot add items.');
Mage::logException($e);
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
}
refresh the page is solution because magento use the form key to validate the data
so when login a customer then session is change according to that and it working
let me know if you have more Questions .
I have added the below code in my controller to add the product to wishlist programmatically. But whenever ajax request goes to the controller it replaces my previously added product from the wishlist and adds the new one to wishlist.
Can somebody please help with this.
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
// Load the customer's data
$customer = Mage::getSingleton('customer/session')->getCustomer();
//echo $customer->getName(); // Full Name
$customerId = $customer->getId(); // First Name
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customerId, true);
$product = Mage::getModel('catalog/product')->load($productId);
$result = $wishlist->addNewItem($product);
$wishlist->save();
echo "added to wishlist";
}
You can try below :
$product = Mage::getModel('catalog/product')->load($productId);
if (!$product->getId() || !$product->isVisibleInCatalog()) {
//$this->__('Cannot specify product.');
}
try {
$requestParams = $this->getRequest()->getParams();
$buyRequest = new Varien_Object($requestParams=array());
$result = $wishlist->addNewItem($product, $buyRequest);
if (is_string($result)) {
Mage::throwException($result);
}
$wishlist->save();
Mage::dispatchEvent(
'wishlist_add_product',
array(
'wishlist' => $wishlist,
'product' => $product,
'item' => $result
)
);
Mage::helper('wishlist')->calculate();
$message = $this->__('%1$s has been added to your wishlist. Click here to continue shopping.',
$product->getName(), Mage::helper('core')->escapeUrl($referer));
} catch (Mage_Core_Exception $e) {
echo $this->__('An error occurred while adding item to wishlist: %s', $e->getMessage());
}
catch (Exception $e) {
echo ($this->__('An error occurred while adding item to wishlist.'));
}
i created custom product price page and also created custom template
and custom template file. and i already override cartController and
edit addAction() method override.
My Code issue: when add to cart
product using ajax when return response data and and i set or add
product information in minicart('in header when "shopping cart" link
hover display cart information') data but product name set but price
not set. it display price is zero. price not set in header shopping
cart content.
Below my addAction() code.
public function addAction()
{
$cart = $this->_getCart();
$params = $this->getRequest()->getParams();
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
/**
* Check product availability
*/
if (!$product) {
$this->_goBack();
return;
}
$cart->addProduct($product, $params);
if (!empty($related)) {
$cart->addProductsByIds(explode(',', $related));
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
if (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()) {
$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
$this->_getSession()->addSuccess($message);
$response['status'] = 'SUCCESS';
$response['message'] = $message;
//My Custom Code start
$this->loadLayout();
$sidebar = $this->getLayout()->getBlock('cart_sidebar')->toHtml();
$response['toplink'] = $toplink;
$response['sidebar'] = $sidebar;
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
}
//$this->_goBack();
//My Custom Code end
}
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
}
}
$url = $this->_getSession()->getRedirectUrl(true);
if ($url) {
$this->getResponse()->setRedirect($url);
} else {
$this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
Mage::logException($e);
$this->_goBack();
}
}
In my custom product price page i wrote below ajax code.
jQuery.ajax({
url: "example.com/checkout/cart/add/product_id/2",
type : 'post',
success: function(data){
var response = data.evalJSON(true);
jQuery('#ajax_loader').hide();
jQuery('.top-cart-content').html(response.sidebar);
}
});
Have you tried creating a new instance of this block in controller rather than getting the block from existing layout?
Say I have a quote from the admin create order with all the products already entered, how could I go about writing some code to add multiple shipping addresses and assign the item to the address.
Ive got some code working, based loosely off the frontend multiship model. The problem I'm having is adding the multiple address and assigning the items to the quote. If I have a standard quote, how can I add the multiple addresses?
I've already tried :
$address = Mage::getModel('customer/address')->load($addressID);
$quote->addShippingAddress($address);
Which seems to only hold one address
The whole function:
public function createMultiOrders() {
// print_r($_POST);
$items = $_POST['item'];
$itemsByAddress = array();
$billingInfo = array();
$session = Mage::getSingleton('adminhtml/session_quote');
$quote = $session->getQuote();
//first we are reorganizing the data provided by javascript into an array based on address ID's
foreach ($items as $key => $item) {
$addID = $item['addressID'];
$itemID = $key;
$qty = $item['qty'];
$itemsByAddress[$addID][] = array('itemID' => $itemID, 'qty' => $qty);
}
// print_r($itemsByAddress);
//now that we have an array of items, seperated by which addressid they goto, we can create the order for each address
foreach ($itemsByAddress as $addressID => $items) {
$address = Mage::getModel('customer/address')->load($addressID);
$quote->addShippingAddress($address);
echo"<br/>address id is $addressID, items are: <br/>";
foreach ($items as $item) {
// $address->addItem($_item);
///add items to order
// echo"id before is $item<br/>";
$itemID = explode('-_', $item['itemID']);
$itemID = $itemID[0];
$qty = $item['qty'];
echo "itemid is $itemID, qty is " . $qty . " <br/><br/><br/><br/>";
}
}
//print_r(get_class_methods($quote));
$shippingAddresses = $quote->getAllShippingAddresses();
try {
foreach ($shippingAddresses as $address) {
$order = $this->_prepareOrder($address);
$orders[] = $order;
Mage::dispatchEvent(
'checkout_type_multishipping_create_orders_single', array('order' => $order, 'address' => $address)
);
}
foreach ($orders as $order) {
$order->place();
$order->save();
if ($order->getCanSendNewEmailFlag()) {
$order->sendNewOrderEmail();
}
$orderIds[$order->getId()] = $order->getIncrementId();
}
Mage::getSingleton('core/session')->setOrderIds($orderIds);
Mage::getSingleton('checkout/session')->setLastQuoteId($quote->getId());
$quote->setIsActive(false)->save();
Mage::dispatchEvent('checkout_submit_all_after', array('orders' => $orders, 'quote' => $quote));
return $this;
} catch (Exception $e) {
Mage::dispatchEvent('checkout_multishipping_refund_all', array('orders' => $orders));
throw $e;
}
Ok I solved the issue and successfully was able to write a script to turn an ordinary admin order into a multi address order. One of the mistakes that messed with me the entire time was the way I loaded the admin quote:
I was loading the session like this
$session = Mage::getSingleton('adminhtml/session_quote');
and it should be
$session = Mage::getModel('adminhtml/session_quote');
Now, as far as assigning each of the quote items to an address, the final code looks like:
$address = Mage::getModel('customer/address')->load($addressID);
echo"<br/>address id is $addressID<br/>";
echo"quote address not set, adding shipping address <br/>";
$quoteAddress = Mage::getModel('sales/quote_address')->importCustomerAddress($address);
$quote->addShippingAddress($quoteAddress);
$quoteAddressItem = $quoteAddress->getItemByQuoteItemId($quoteItem->getId());
if ($quoteAddressItem) {
echo"increasing item quantitiy for quote address<br/>";
// $quoteAddressItem->setQty((int) ($quoteAddressItem->getQty() + $qty));
} else {
echo"setting customer id for quote item<br/>";
$quoteItem->setCustomerAddressId($quoteAddress->getCustomerAddressId());
echo"adding item to quote address<br/>";
$quoteAddress->addItem($quoteItem)->setQuote($quote);
echo"adding item to quote collection<br/>";
if (!$quoteAddress->getItemsCollection()->getItemById($quoteItem->getId())) {
$quoteAddress->getItemsCollection()->addItem($quoteItem)->save();
}
$quoteAddress->setCollectShippingRates(TRUE);
$quoteAddress->collectShippingRates();
$quoteAddress->save();
$quoteItem->save();
$quote->save();
}
I've built a custom script to add and remove items to the wishlist using AJAX. Adding products is not a problem but I can't figure out how to remove an item. The Magento version is 1.5.1.0.
The script is in /scripts/ and looks like this:
include_once '../app/Mage.php';
Mage::app();
try{
$type = (!isset($_GET['type']))? 'add': $_GET['type'];
$id = (!isset($_GET['id']))? '': $_GET['id'];
$session = Mage::getSingleton('core/session', array('name'=>'frontend'));
$_customer = Mage::getSingleton('customer/session')->getCustomer();
if ($type != 'remove') $product = Mage::getModel('catalog/product')->load($id);
$wishlist = Mage::helper('wishlist')->getWishlist();
if ($id == '')
exit;
if ($type == 'add')
$wishlist->addNewItem($product);
elseif ($type == 'remove')
$wishlist->updateItem($id,null,array('qty' => 0));
$products = Mage::helper('wishlist')->getItemCount();
if ($type == 'add') $products++;
if ($type == 'remove') $products--;
$result = array(
'result' => 'success',
'type' => $type,
'products' => $products,
'id' => $id
);
echo json_encode($result);
}
catch (Exception $e)
{
$result = array(
'result' => 'error',
'message' => $e->getMessage()
);
echo json_encode($result);
}
So when I request the script with "remove" as $type and the wishlist item id as $id I get the following error:
Fatal error: Call to a member function getData() on a non-object in /[magento path]/app/code/core/Mage/Catalog/Helper/Product.php on line 389
When I look at the function updateItem() in /app/code/core/Mage/Wishlist/Model/Wishlist.php it expects a "buyRequest", but I can't figure out what that is.
I have no time to debug whatever goes wrong with your code, but using the normal convention of deleting entities should work:
Mage::getModel('wishlist/item')->load($id)->delete();
Just have a look at the removeAction of Mage_Wishlist_IndexController.
You have to load the Wishlist item by its ID and then you can call the delete() method.
I know this question is old but since I just ran into the same problem with magento 1.7.0.2 I want to share the solution.
To make it work you need to use the method updateItem as follow
$wishlist->updateItem($id, array('qty' => 10));
Instead of
$wishlist->updateItem($id, null, array('qty' => 10));
You can't use this method to set an item qty to 0. It will automatically set it to a minimum of 1 unless you use the delete method.
Hi use this code to remove a product having productid $productId of a customer having customerid $customerId.
$itemCollection = Mage::getModel('wishlist/item')->getCollection()
->addCustomerIdFilter($customerId);
foreach($itemCollection as $item) {
if($item->getProduct()->getId() == $productId){
$item->delete();
}
}