Magento : Add product to wish list programatically - magento

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

Related

Programatically adding product to magento cart not working at the first time only

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 .

can't renderer mini cart(top header shopping cart) price using when add to cart using ajax in magento

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?

Creating orders programmatically

I try to create an order in code, but sometimes the code works, but sometimes it goes wrong with exception "The requested Payment Method is not available." (first browser request is ok, but the second one goes wrong, etc..).
My code is:
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
} else {
$customer = Mage::getModel('customer/customer');
$email = 'test#example.com';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->setStoreId(Mage::app()->getStore()->getId());
$customer->loadByEmail($email);
Mage::getSingleton('customer/session')->loginById($customer->getId());
}
$customAddress = Mage::getModel('customer/address')
->setCustomerId($customer->getId())
->getCustomer();
$customAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customAddressId) {
$customAddress = Mage::getModel('customer/address')->load($customAddressId);
}
Mage::getSingleton('checkout/session')->getQuote()
->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress))
->setShippingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load(2);
$cart = Mage::getSingleton('checkout/cart');
$cart->truncate();
try {
$cart->addProduct($product, array('qty' => 2));
$cart->save();
$message = $this->__('%s was successfully added to your shopping cart.', $product->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
} catch (Exception $ex) {
echo $ex->getMessage();
}
$storeId = Mage::app()->getStore()->getId();
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('register');
$checkout->saveShippingMethod('flatrate_flatrate');
$checkout->savePayment(array('method' => 'banktransfer'));
try {
$checkout->saveOrder();
} catch (Exception $ex) {
echo $ex->getMessage();
}
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
Mage::getSingleton('customer/session')->logout();
I checked your code in my local server, It s working fine 1st time, but second time it shows error like The requested Shipping Method is not available not like you mentioned above. But after I enabled that shipping method it working fine, So try to enable the shipping and payment methods that you used in your code in admin..

Magento - Adding products to cart using a loop

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.

Magento Add to cart not working

Writting custom script to add product to particular customer.
In this way.
$product = Mage::getModel('catalog/product')->load($id);
$cart = Mage::getSingleton('checkout/cart');
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
$req = Mage::app()->getRequest();
$request['qty'] = $selected_qty[$i];
$request['product'] = $value;
$prod_req = new Varien_Object($request);
try {
$cart->addProduct($product, $prod_req);
$cart->save();
$msg .= "<p>".$product->getName(). " ==> ".$selected_qty[$i] . " items <br/></p>";
}
catch (Exception $ex) {
$err .= "<p>".$ex->getMessage(). " <br/></p>";;
}
Customer session shows logged in customer details, but this doesn't adding the product to the cart. Whats the problem, could anyone find out.
Thanks
I got it working by in the same way from inchoo site. Thanks to them.
Here is what i have now.
$product = Mage::getModel('catalog/product')->load($value);
$cart = Mage::getSingleton('checkout/cart');
$params = array(
'product' => $value,
'related_product' => null,
'qty' => $selected_qty[$i],
);
try {
$cart->addProduct($product, $params);
$cart->getItems()->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$msg .= "<p>".$product->getName(). " ==> ".$selected_qty[$i] . " item(s) <br/></p>";
}
catch (Exception $ex) {
$err .= "<p>".$ex->getMessage(). " <br/></p>";;
}
Its working perfectly.

Resources