Mage::init('default') causing error in Module - php

I have test php script running outside of Magento that will add an item to the cart. Works great. This code was found here and used by many people in quite a few posts. When I place this code into an existing module, the item is not added, from a fresh session. If I go to the store and add a regular product (have an item in my cart) the module will add the item properly. I Know the code to add the item works. The problem I have is with creating the FIRST instance of a cart.
This code works just fine if already have a normal magento product in my cart:
// this section of code only works if the customer already has a cart item added (cart established)
// for some reason this script fails when no cart exists
$session = Mage::getSingleton('customer/session');
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$productId=971;
$productInstance = Mage::getModel('catalog/product')->load($productId);
$param = array(
'product' => $productId,
'qty' => $rfqdata['option_quantity'],
'options' => array(
27 => $rfqdata['option_layers'], // Layers
26 => $rfqdata['option_thickness'], // Thickness
25 => $rfqdata['option_length'], // Length
24 => $rfqdata['option_width'], // Width
23 => $rfqdata['option_color'], // Color
22 => $rfqdata['option_finish'], // Finish
29 => $rfqdata['option_rush'], // Rush
30 => 'tbd' // RFQ Number
)
);
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $param);
$session->setCartWasUpdated(true);
$cart->save();
This somehow causes an error, and the module addtocart action is not completed. I cannot find any useful error messages. I have searched 100s of pages on stack, google, and I can find nothing to resolve this issue. Obviously my module is worthless if it doesn't work from page load 1.
I tried to post this before and got no response. I really need some help. If you cannot answer, can you tell me where I can find paid Magento support?

here is the solution, it was very hard to find too....
if(empty($quote)){
$checkout = Mage::getSingleton('checkout/session');
$quote = $checkout->getQuote();
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()) {
// look up customer
$customerSession = $session->getCustomer();
$customer = Mage::getModel('customer/customer')->load($customerSession->getId());
$quote->assignCustomer($customer);
$quote->setIsMultiShipping(false);
}
$quote->save();
}

Related

Prestashop 1.7.x - How do I add product's carriers in product list?

Today I'm adding visual stickers to my products in order to show the user which carriers will be available, so they won't have a cart with 10 products delivered and 1 to pickup in store.
They'll immediately know what they can do.
No problem on single product page, adding this in ProductController.php is enough :
$this->context->smarty->assign(array(
'pictures' => $pictures,
'textFields' => $text_fields,
'carriers' => $this->product->getCarriers(),
));
The point comes to product-list page ... I can't seem to find out what I can do to link the carriers to each product of the category.
By looking at ProductListingFrontController.php, I noticed i could get all category products in $variables here :
protected function doProductSearch($template, $params = array(), $locale = null)
{
if ($this->ajax) {
ob_end_clean();
header('Content-Type: application/json');
$this->ajaxRender(json_encode($this->getAjaxProductSearchVariables()));
return;
} else {
$variables = $this->getProductSearchVariables();
Does anybody have already done something like this in Prestashop 1.7.x ?
I would suggest you to build a very simple module and take advantage of native Prestashop hooks displayProductListReviews and displayProductAdditionalInfo to return your desired content.
You can easily access all product properties inside the hook $params to get the available carriers.

Products show only in admin when adding via Magento 1.9 Custom Wishlist SOAP API

Requirement: I am a newbie in magento trying to make a custom SOAP API in Magento 1.9 for managing wishlist. I need to connect it to an android application being developed in ionic V1.
At first i tried to use this extension magento-api but could not find a way to maintain session information in android. So, i moved to developing my own API.
I am able to fetch wishlist information(wishlist_id, items etc) and add to it.
Issue: But after adding a product in the wishlist via soap call, it is only shown in the admin area for the customer and not on the front-end of the website(User is logged in). Only products added from front-end(browser) are shown on front-end wishlist page.
After comparing the functionality from the front-end(/app/code/core/Mage/Wishlist/controllers/IndexController.php) with my Api.php(shown below) seems like my $buyRequest variable is missing some 'form-key' but i do not understand magento too much to understand this.
I have added the Api.php at /app/code/core/Mage/Wishlist/ModelApi.php.
My code to add product to wishlist is as follows:
public function create($customer_id, $product_id, $store = null){
$return_result = array(
'code' => 0,
'msg' => null,
'model' => null,
'customer_id' => $customer_id,
'product_id' => $product_id
);
$buyRequest = new Varien_Object(array());
$params = array('product' => $product_id,
'qty' => 1,
'store_id' => $store,
);
$buyRequest->setData($params);
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer_id, true);
$product = Mage::getModel('catalog/product')->load($product_id);
$result = $wishlist->addNewItem($product, $buyRequest);
Mage::helper('wishlist')->calculate();
if($result){
$return_result['msg'] = 'Product '.$product_id.' Added ';
$return_result['model'] = $result;
}
return json_encode($return_result);
}
I used the following link to implement the add functionality and used some code in the from the /app/code/core/Mage/Wishlist/controllers/IndexController.php file: add catalog product in wishlist programmatically in magento
Any help would be appreciated.

Magento php add to cart with Custom price

I have the following issue:
I make calculations via jQuery in the frontend and want to add a product to the cart with the price calculated in the frontend.
I already wrote a custom module with an AjaxController to achieve the adding to cart part, but I know struggle with setting the custom price.
My script looks like this:
$_prod = json_decode(Mage::app()->getRequest()->getPost('zapfsaeule_product'));
$id = 347; // there is only this one bundle product added to the cart viar this scipt, so a static id is enough.
$params = array(
'product' => $id,
'related_product' => null,
'bundle_option' => array(
6 => 17, // static options for testing purpouses
5 => 13), //
'qty' => 1 // static qty for testing as well
);
$cart = Mage::getSingleton('checkout/cart');
$product = new Mage_Catalog_Model_Product();
$product->load($id);
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$this->getResponse()->setBody('true'); // setting response to true, because its an ajax request.
$this->getResponse()->setHeader('Content-type', 'text/plain');
That's the code for adding the product.
For setting the price I tried the approach as mentioned in this thread on stackexchange:
https://magento.stackexchange.com/questions/4318/dynamically-calculated-prices-save-before-add-to-cart
But it didn't work. I guess the event observed here doesn't occur in my case, because I wrote a custom script.
But then there still would be the problem, IF the observer approach would work, how would I pass the calculated price to the observer?
I hope you understand the problem and can help me solve it.
Thanks in advance!
Best regards,
Martin
Reading through Mage_Checkout_Model_Cart::addProduct(), there doesn't appear to be a way to set the item's price from the parameters. Instead, you'll need to add the product, then grab the resulting item, and set its price:
$cart->addProduct($product, $params)
->save();
// grab the corresponding item
$item = $cart->getQuote()->getItemByProduct($product);
// set its custom price
$item->setOriginalCustomPrice($customPrice)
->save();
Haven't had the time to try this out, but it should be the right idea. Make sure that you set the original_custom_price field (using setOriginalCustomPrice()), not one of the other prices. The other prices are recalculated during the totals process.
This comes pretty late, but I just stumbled upon this.
I got it to work like this:
$cart = Mage::getSingleton('checkout/cart');
$cart->addProduct($product, 1); // 1 = qty. Pass your qty and params.
$item = $cart->getQuote()->getItemByProduct($product);
$item->setCustomPrice(0); // or some other value
$item->setOriginalCustomPrice(0); // or some other value
$item->getProduct()->setIsSuperMode(true); // this is crucial
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
If the params don't work, fetch the returned item from $cart->addProduct and change the price on the item before saving the cart.
$item = $cart->addProduct(...);
$item->setCustomPrice(...); {or whatever price attribute you like to set}
$cart->save();

Unable to set Shipping Method in Magento order create script

I am having trouble getting my Script to create an order on my live site that uses Magento 1.7. The error I am getting is “please specify a shipping method” more detail is
blockquote Fatal error: Uncaught exception 'Mage_Core_Exception' with message 'Please specify a shipping method.' in /home/mysite/public_html/app/Mage.php:594 Stack trace: #0 /home/mysite/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php(303): Mage::throwException('Please specify ...') #1 /home/mysite/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php(222): Mage_Sales_Model_Service_Quote->_validate() #2 /home/mysite/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php(238): Mage_Sales_Model_Service_Quote->submitNominalItems() #3 /home/mysite/public_html/apitest/magento_order_create.php(82): Mage_Sales_Model_Service_Quote->submitAll() #4 {main} thrown in /home/mysite/public_html/app/Mage.php on line 594
I am trying to use the script below to create the order and I am passing the skus and quantities in the post from another page. `
<?php
// Link Mage Class
require ('../app/Mage.php');
// Initialize Magento framework
Mage::app('mysite');
//create a cart
$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore('mysite')->getId());
//Get Customer by Id
$customer = Mage::getModel('customer/customer')->load('1');
//attach customer to cart
$quote->assignCustomer($customer);
//attach products
foreach ($_POST as $sku=>$qty)
{
$product = Mage::helper('catalog/product')->getProduct($sku,Mage::app()->getStore()->getId(), 'sku');
$buyInfo = array(
'qty' => $qty,
// custom option id => value id
// or
// configurable attribute id => value id
);
$quote->addProduct($product, new Varien_Object($buyInfo));
}
//get and set customer billing address
//need to work on this encase we use diffrent billing and shipping addresses
$addressData = Mage::getModel('customer/address')->load('1');
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
// set shipping and payment methods. assumes freeshipping and check payment
// have been enabled.
/*
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping')
->setPaymentMethod('checkmo');
*/
// THIS IS WHERE THE ERROR SEEMS TO BE
$quote->getShippingAddress()->setShippingMethod('freeshipping_freeshipping');
$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->getShippingAddress()->collectShippingRates();
//set payment method
$quote->getPayment()->importData(array('method' => 'checkmo'));
//save cart and check out
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Created order %s\n", $order->getIncrementId());
`
The above script originally came from http://pastebin.com/8cft4d8v
and it works like a charm on my test environment (also 1.7). I have commented out the original shipping method code and broke is out into separate lines.
The live site has two sites and two stores, I have made sure that free shipping is enabled on the backend and tested that it shows up when I run this script.
<?php
// Link Mage Class
require ('../app/Mage.php');
// Initialize Magento framework
Mage::app('mysite');
$methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
var_dump($methods);
I am fairly certain the address is set correctly, if I echo is out to the screen that address is there.
I have tried reading the documentation, looking at other sample code and changing parts of it to see if I can get the shipping method set, but no luck.
Well the main solution seems to be something that was solved during a server reboot. But I am also going to post the final script that we are going to use. For some reason setting shipping method on a quote object does not seem to work, so I also went back to the “orginal” script that I had found on http://pastebin.com/8cft4d8v. I also got rid of some lines that did not seem to matter if they existed or not. Hope this may help someone down the line
<?php
// Link Mage Class
require ('..\app\Mage.php');
// Initialize Magento framework
Mage::app('my');
//create a cart
$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore('default')->getId());
//Get Customer by Id
$customer = Mage::getModel('customer/customer')->load('1');
//attach customer to cart
$quote->assignCustomer($customer);
//attach products
foreach ($_POST as $sku=>$qty)
{
$product = Mage::helper('catalog/product')->getProduct($sku, Mage::app()->getStore()->getId(), 'sku');
$buyInfo = array(
'qty' => $qty,
// custom option id => value id
// or
// configurable attribute id => value id
);
$quote->addProduct($product, new Varien_Object($buyInfo));
}
$billingAddress = $quote->getBillingAddress()->addData();
$shippingAddress = $quote->getShippingAddress()->addData();
// set shipping and payment methods. assumes freeshipping and check payment
// have been enabled.
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('flatrate_flatrate');
$quote->getPayment()->importData(array('method' => 'checkmo'));
//save cart and check out
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Created order %s\n", $order->getIncrementId());

Add product to cart in observer

I need to create a possibility for customers to offer a one product free of charge (as an example) in Magento shop. I figured out most of things from this post, but now I have one problem. I am created an Observer method that is executed on checkout_cart_product_add_after. And there I have some code (its just a part of whole thing):
$productId = $observer->getProduct()->getId();
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
Mage::getModel('core/session')->addNotice('Product id: '.$productId);
foreach ($items as $item) {
if ($item->getProduct()->getId() == $productId) {
$itemId = $item->getItemId();
$cart = $cartHelper->getCart()->removeItem($itemId)->save() ;//It WORKS!!!!!!!!!!!!
$product = Mage::getModel('catalog/product')->load($productId);
$cart->addProduct($product, $this->_getRequest()->getParams());
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
break;
}
}
So first of all my code adds a product to cart with 0.00 price (product as an example) based on some request parameters. Thats part works fine so it is not posted here. The second part (that I posted above) must delete an existing product and replace it with product with normal price. Almost everything works fine except one thing - the line $cart->addProduct($product, $this->_getRequest()->getParams()); don't work and I cant understand why (no errors, no exceptions, no logs).
_getRequest method looks like this:
protected function _getRequest()
{
return Mage::app()->getRequest();
}
And if I log an $this->_getRequest()->getParams() there is will be something like this:
2012-04-09T14:46:56+00:00 DEBUG (7): Array(
[uenc] => aHR0cDovL2xvY2FsaG9zdC93b3AvZmVhdHVyZWQvY2xhc3NpYy1saW5lLXBvbHkuaHRtbA,,
[product] => 50
[related_product] =>
[bundle_option] => Array(
[20] => 75
[21] => 84
[22] => 94
)
[qty] => 1
[send-request] => 0
)
So why that $cart->addProduct($product, $this->_getRequest()->getParams()); will not work? How to do it right? Maybe it is better to use addAction() of Mage_Checkout_CartController (overwrite it)?
Sorry for my language. Thanks for answers. Hope somebody can help me...
I'll answer my question to clarify things for anybody, who will stumble the same problem.
The code:
$cart->addProduct($product, $this->_getRequest()->getParams());
will not work because I call $cart->save() before it and than tried to do the same after it and that was the problem. When I removed first $cart->save() it is worked just fine.

Categories