Magento Add to cart not working - magento

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.

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 .

Magento : Add product to wish list programatically

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

Magento can not add product programmatically

i have use below code to add product in magento but not success ,anyone know how to do?
code here
code txt file
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$product = new Mage_Catalog_Model_Product();
$product->setSku('A123');
$product->setAttributeSetId(4);
$product->setTypeId('simple');
$product->setName('Some cool product name');
$product->setCategoryIds(array(19));
$product->setWebsiteIDs(array(1));
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setPrice(39.99);
$product->setWeight(4.0000);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setStatus(1);
$product->setTaxClassId(0);
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
}
catch (Exception $ex) {
}
?>
i hope it may bemage.php path issue.Try put proper of mage file path
Suppose,My Magento path is /home/abc/www/www/ in server.
and my script file location location in /home/abc/www/www/try/dot/myscript.php
If you try to include mage.php from myscript.php then
$mageFilename = '/home/abc/www/www/app/Mage.php'
or
$mageFilename = '../../app/Mage.php'
i have run your script with modify mage.php file location call in script.it is works
I've been using this code to add/update products on Magento.
<?php
include_once("app/Mage.php");
Mage::app();
umask(0);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$counter = 0;
I have this function to get (or create) a product by SKU:
function GetProduct($sku)
{
global $counter;
echo $sku;
$p = Mage::getModel('catalog/product');
$productId = $p -> getIdBySku($sku);
if($productId)
{
echo "!";
$p -> load( $productId );
}
else
{
$p->setTypeId('simple');
$p->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$p->setStatus(1);
$p->setTaxClassId(7);
$p->setWebsiteIDs(array(1));
$p->setStoreIDs(array(1));
$p->setAttributeSetId(4);
$p->setSku($sku);
}
echo "...";
$counter++;
echo " ".$counter;
return $p;
}
Here's the function to save the product:
function SaveProduct($p)
{
try
{
if (is_array($errors = $p->validate()))
{
$strErrors = array();
foreach($errors as $code=>$error)
{
$strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
echo $strErrors[0];
}
$this->_fault('data_invalid', implode("\n", $strErrors));
}
$p->save();
echo "\n";
}
catch (Mage_Core_Exception $e)
{
$this->_fault('data_invalid', $e->getMessage());
}
}
And finally I'm calling like this:
$product = GetProduct('sku1');
$product->setData('thumbnail_label', 'sku1');
SaveProduct($product);
unset($product);
$product = GetProduct('sku2');
$product->setData('url_path', 'plastic-hat.html');
SaveProduct($product);
unset($product);
$product = GetProduct('sku3');
$product->setData('thumbnail_label', 'sku3');
SaveProduct($product);
unset($product);
$product = GetProduct('sku4');
$product->setData('thumbnail_label', 'sku4');
SaveProduct($product);
unset($product);
$product = GetProduct('sku5');
$product->setData('thumbnail_label', 'sku5');
SaveProduct($product);
unset($product);
I run this code from the command-line as there is a memory leak running it this way. You can only get so many products updated before it blows the memory and you have to edit and re-run the code to keep going, but it works and it's relatively fast.
You should be able to slot your code in quite nicely.

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.

Resources