Magento Wishlist - Remove item - magento

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();
}
}

Related

I want to know how Magento save order when return after successful payment in paypal_express

Here is a condition in my latest project where I have to create order after successful payment done through Paypal Express programatically.
When I do it through Magento normal flow it is working very fine, but I want to do it programatically myself.
I tried this but it gives error that payment method is not available.
$quote->collectTotals();
$service = Mage::getModel("sales/service_quote", $quote);
$service->submitAll();
$order = $service->getOrder();
if($order) {
Mage::dispatchEvent("checkout_type_onepage_save_order_after", array("order" => $order, "quote" => $quote));
try {
$order->sendNewOrderEmail();
}
catch(Exception $e) {
Mage::logException($e);
}
}
I tried this also but nothing works
$quote = Mage::getModel("sales/quote")->setStore(Mage::getSingleton("core/store")->load(1))->load($shoppingCartId);
$checkout = Mage::getSingleton('paypal/express_checkout', array(
'config' => Mage::getModel('paypal/config', array(Mage_Paypal_Model_Config::METHOD_WPP_EXPRESS)),
'quote' => $quote,
));
$detailsBlock = new Mage_Paypal_Block_Express_Review_Details();
$detailsBlock->setQuote($quote);
$checkout->updateShippingMethod("ups_GND");
$session->setLastQuoteId($shoppingCartId)->setLastSuccessQuoteId($shoppingCartId);
$order = $checkout->getOrder();
if ($order){
$session->setLastOrderId($order->getId())->setLastRealOrderId($order->getIncrementId());
echo "<br>".$order->getData();
}
Any help is much appreciated. :)

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

filter data from complex values in magento grid

Hi I have added a new column in a shipment grid as below
$this->addColumn('telephone', array(
'header' => Mage::helper('sales')->__('Billing Phone'),
'index' => 'telephone',
'renderer'=> new OSP_Adminhtml_Block_Customer_Renderer_BillingPhone()
));
in this i am using a renderer to show custom values as below
public function render(Varien_Object $row) {
$customer_id = $row->getData('customer_id');
if( $customer_id > 0 ) {
// get member_id (club canon)
$customer = Mage::getModel('customer/customer')->load($customer_id);
if( is_object( $customer ) ) {
$value = $customer->getData('mobile');
}
}else{
$id = $row->getData('order_increment_id');
$order = Mage::getModel('sales/order')->loadByIncrementId($id);
$value = $order->getBillingAddress()->getTelephone();
}
return $value;
}
which is working fine and it shows data properly on the basis of
condition in renderer.
But the problem is now I need to filter the data also which is not
working as it looks for data in only one column as telephone or mobile
I have read about filter_condition_callback but unable to make the work . Can you please suggest me how can I make this work.
Thanks in advance
1.Add line filter_condition_callback to column, like that:
$this->addColumn('telephone', array(
'header' => Mage::helper('sales')->__('Billing Phone'),
'index' => 'telephone',
'filter_condition_callback' => array($this, '_someCallBackFunction'),
'renderer'=> new OSP_Adminhtml_Block_Customer_Renderer_BillingPhone()
));
After you added this line in your column, Magento will call this callback function, look app/code/core/Mage/Adminhtml/Block/Widget/Grid.php in 468 line.
2.In your block grid file create _someCallBackFunction function, which will take two parameters, $collection - collection object not loaded, and $column Mage_Adminhtml_Block_Widget_Grid_Column
protected function _someCallBackFunction($collection, $column)
{
$value = $column->getFilter()->getValue();
if ($value === null) { //here check if filter is not null
return $this;
}
/**
* Here you can add filter to collection
* or do other manipulations with collection.
* As example you can check filter value and filter collection.
*/
if ($value != 0) {
$collection->addFieldToFilter('telephone', array('neq' => 0));
}
return $this;
}

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.

How to send Product Selected Custom Option Sku Field to cart page in Magento

I am working in a scenario I want to send Product selected Custom Option SKU in cart page have founded the array which is sent to cart in case of custom options.
Here is a Function called getProductOptions() in which Product Option Array is created and sent to cart. At this point, I want to send selected Custom Option SKU field to cart.
I have the following code:
public function getProductOptions()
{
$options = array();
if ($optionIds = $this->getItem()->getOptionByCode('option_ids')) {
$options = array();
foreach (explode(',', $optionIds->getValue()) as $optionId) {
if ($option = $this->getProduct()->getOptionById($optionId)) {
//echo $optionId;
echo "hhhhhhhhhhhhh";
//print_r( $option->getId());
//echo Mage::getModel('catalog/product')->getOptionSku($option);
//die();
//print_r( $option->getOptionSku());
//echo Mage_Catalog_Model_Product_Option_Type_Select::getOptionSku());
$quoteItemOption = $this->getItem()->getOptionByCode('option_' . $option->getId());
//echo $option->getQuoteItemOption($quoteItemOption);
$group = $option->groupFactory($option->getType())
->setOption($option)
->setQuoteItemOption($quoteItemOption);
$options[] = array(
'label' => $option->getTitle(),
'value' => $group->getFormattedOptionValue($quoteItemOption->getValue()),
'print_value' => $group->getPrintableOptionValue($quoteItemOption->getValue()),
'option_id' => $option->getId(),
'option_type' => $option->getType(),
'custom_view' => $group->isCustomizedView(),
'option_sku'=>//What should i call here to send Selected option SKU to this Array
);
}
}
if ($addOptions = $this->getItem()->getOptionByCode('additional_options')) {
$options = array_merge($options, unserialize($addOptions->getValue()));
}
}
return $options;
}
It looks like the bit you're missing is
'option_sku' => $this->getItem()->getSku()
Don't modify the block itself, just change the rendered template to add a for this field. Grab the data from the $_item variable, and echo it out to the user. That should require no modifications of the block.

Resources