13 replies [Last post]
setfree's picture
Offline
Uber Donor
Joined: 12/16/2007
Juice: 436
Was this information Helpful?

I have developed a custom module and need to dynamically add a product to the cart. Is there an API to allow me to do this?

Something like would be my dream hook Smiling

<?php
  mymodule_add_product_to_cart
($nid, $qty, $data)
?>

Where I could submit the product NID, the quantity to add and any extra data and the item would be put in the cart and the user would be redirected to the cart page.

Is something like this possible? Or is there another approach that I should be looking at?

Thanks for any help!

slayerment's picture
Offline
Uber Donor
Joined: 01/06/2008
Juice: 86
Re: API to add product to cart?

I am pretty sure the solution is the core cart_links module which will allow you to link to a product using a specific syntax. Take a look here: http://www.ubercart.org/contrib/1427

setfree's picture
Offline
Uber Donor
Joined: 12/16/2007
Juice: 436
Re: Re: API to add product to cart?

Nice. Thank you for the tip, it looks like this will work. Silly me, it was right there in core all along. I just never paid attention to this module and haven't been in the module list for a while...

Thanks again~

Complete Computer Care

Ryan's picture
Offline
Joined: 08/07/2007
Juice: 15438
Re: Re: Re: API to add product to cart?

You can also check out an article on uc_cart_add_item() that I posted to my company site's Ubercart resources section.

setfree's picture
Offline
Uber Donor
Joined: 12/16/2007
Juice: 436
Re: Re: Re: Re: API to add product to cart?

Thanks Ryan! That's a great writeup and perfect for what I want to do Smiling

setfree's picture
Offline
Uber Donor
Joined: 12/16/2007
Juice: 436
Ryan, I read your article

Ryan,

I read your article and have started implementing the functionality with uc_cart_add_item(). This is working good for adding a dynamic price into the user's cart but setting the product price to $1 and using qty to get to the actual price that the customer is paying.

Question: Is there a more elegant way to adjust the price dynamically? I think it would be nice if I could have it add qty 1 and adjust the price in the cart to match what the custom is paying.

On Ubercart 2.x, what is the best way to handle this?

Thanks!

Ryan's picture
Offline
Joined: 08/07/2007
Juice: 15438
Re: Ryan, I read your article

I believe what you'd need to do is add a variable to the item's data array that represented the custom price using hook_add_to_cart_data(). Then you can use hook_cart_item() to alter the price of the product when the shopping cart is loaded. This is what I plan to do for a "Variable Price" product feature in the near future. We're still securing community funding, but details are on Commerce Guys.

setfree's picture
Offline
Uber Donor
Joined: 12/16/2007
Juice: 436
Need more help please :)

It appears that hook_add_to_cart_data() is not called when using uc_cart_add_item. I have tested by using the product form's 'Add to Cart' button and it is called as expected, but not when using uc_cart_add_item. Is this a bug or feature?

My plan was to use a menu path to called a function. This function would grab the user's amount due and use hook_add_to_cart_data() to store the amount in a variable. Then use hook_cart_item() to adjust the product's price in the cart. However, this falls apart without hook_add_to_cart_data() firing. Is there a another/better solution?

BTW - I will be chipping in the the Donation Support initiative, and of course, more Ubercart.

Thanks!

Lyle's picture
Offline
AdministratoreLiTe!
Joined: 08/07/2007
Juice: 6846
Re: Need more help please :)

hook_add_to_cart_data() is generally used to create the $data parameter that is passed into uc_cart_add_item(). Look at uc_product_add_to_cart_form_submit(). The tricky part is creating some form values to pass in to hook_add_to_cart_data(), but mostly it's just 'nid', 'qty', and an array of attribute options.

setfree's picture
Offline
Uber Donor
Joined: 12/16/2007
Juice: 436
One last question (hopefully) adjust $item in cart

Thank you for all of the help. I have made quite a bit of progress in developing a dynamic price solution! I am stuck on one last bit though and need just a tad more help.

First off, here is what I have now.

  • Customer clicks "Pay Now" link and is directed to custom add to cart form.
  • This form hides the qty field and pre-fills the amount of the customer's balance. They can change this value to any amount that they want to pay.
  • When custom form is submitted the payment amount is stored in a data field called 'pay' using hook_add_to_cart_data()
  • The 'pay' amount is loaded into the cart item's price field using hook_database_cart_item() and displays correctly.
  • This all works great so far!

Now I need to be able to allow the customer to change the amount they are paying after the item has been added to the cart.

I would love to be able to get a handle on the $item when a user submits the custom form again in a way that would allow me to adjust the data->pay field. There would only ever be qty 1 of this item, so if the user uses the custom add to cart form to submit the item again, it would simply update the pay price of the item that is already in the cart. Then I could use this same form to allow the customer to edit the price after it's in the cart also.

Right now, if I add the item again with the same pay price it updates the qty. If I add the item again with a different pay price it adds a new item to the cart.

I can get a handle on the form using hook_form_submit(), and use $items = uc_cart_get_contents() to get the cart items. But I don't know of any way to adjust the $item from here (or any where else)

I hope this makes sense. Any ideas are most welcome and I will, of course, post all working code when I get this fully functional.

Here's some snippets of what I have now that may help in understand what I'm trying to do:
__________________________________________________________________

<?php
// Build a custom add to cart form.
function ilt_database_multi_add_form() {
  global
$user;
   
$account = user_load(array('uid' => $user->uid));

 

// Set the product NID to use (Application)
 
$nid = (288);
 
 
// Build a custom add to cart form.
 
$form = array();

 

// Make the products array in the form a tree.
 
$form['products'] = array(
   
'#tree' => TRUE,
  );

 

// Add a quantity field for each product.
 
$form['nid'] = array('#type' => 'value', '#value' => $nid);
 
$form['qty'] = array('#type' => 'hidden', '#value' => 1);

 

$form['price'] = array(
   
'#prefix' => 'Your current balance is $' . $account->ilt_database_total_due .'.',
   
'#type' => 'textfield',
   
'#title' => t('Payment Amount'),
   
'#size' => 16,
   
'#required' => true,
   
'#default_value' => $account->ilt_database_total_due,
  );

 

// Add an add to cart button.
 
$form['add_to_cart'] = array(
   
'#type' => 'submit',
   
'#value' => t('Submit Payment'),
  );

  return

$form;
}

// Custom add to cart form submit handler
function ilt_database_multi_add_form_submit($form, &$form_state) {
   if (
$form_state['values']['nid'] == 288){
     
$items = uc_cart_get_contents();
      foreach (
$items as $item){
        if (
$item->nid == 288) {
         
$item->data['pay'] = '*** NEW AMOUNT ***'; // I think this is where I would like to update to the new PAY amount         
       
}
      }
    }
 
// Display a message and redirect to the cart.
 
$form_state['redirect'] = uc_cart_add_item($form_state['values']['nid'], $form_state['values']['qty'],  module_invoke_all('add_to_cart_data', $form_state['values']));
}

// Store customer's PAY amount in data pay field
function ilt_database_add_to_cart_data($form_values) {
  return array(
'pay' => $form_values['price']);
}

// Adjusts the item price to reflect what the customer is paying
function ilt_database_cart_item($op, &$item) {
  switch (
$op) {
    case
'load':
     
$item->price = $item->data['pay'];
      break;
  }
}
?>
AsciiKewl's picture
Offline
Joined: 04/07/2009
Juice: 2
Example code for variable price

Here is some code I got working this morning that does this, support module name replaces with "xxx":

/**
  * Add the items from the dynamic form to the cart.
  *
  * @param $products
  *   An array of arrays, each sub array being the products
  *   Each product array has the following keyed values
  *     'nid' = nid of product (required)
  *     'description' = override title of product (optional)
  *     'price' = override the price (optional)
  */

function xxx_add_variable_products_to_cart($products = array()) {
  foreach ( $products as $product ) {
    if (isset($product['price'])) {
      $data['variable_price']=$product['price'];
    }
    if (isset($product['description'])) {
      $data['variable_description']=$product['description'];
    }
    uc_cart_add_item($product['nid'],$product['qty'],$data,NULL,FALSE,FALSE);
  }
}

/* Implement hook_cart_item */
function xxx_cart_item($op,&$item) {
  if ($op == "load") {
    if (isset($item->data['variable_price'])) {
      $item->price = $item->data['variable_price'];
    }
    if (isset($item->data['variable_description'])) {
      $item->title = $item->data['variable_description'];
    }
  }
}

And a test example to use the code:

function thrifty_add_to_cart_test ( ) {
  $products = array();
  $products[] = array (
    'nid' => 27,
    'qty' => 1,
    'description' => "Some description",
    'price' => 123.45,
  );
  thrifty_add_variable_products_to_cart($products);
}

I hope this helps someone as it took me a bit of time to figure out what can/should go where.

theamoeba's picture
Offline
Joined: 05/18/2008
Juice: 17
Re: Example code for variable price

This is an awesome piece of code. Thank you very much Smiling.
I modified it slightly for my needs because I only needed to update the price and nothing much else, but it is working really well.

~ theamoeba

aubede's picture
Offline
Joined: 12/16/2010
Juice: 3
similar problem

Hi am stuck with a similar problem.
Am using node checkout module in drupal along with a custom module. so basically what i need is that when a node is added to the cart during checkout, i need to update the cart's cost of the purchase by some variable amount (which i calculate programmatically). after that i also need to render the "update cart" inaccessibe to the current user, so that he can either checkout with the incremented rate or cancel.
Any help would be highly appreciated. thanks!

venkatadapa's picture
Offline
Joined: 07/31/2011
Juice: 9
Prevent redirect to cart page after product added to cart

Hi,

I am working on D6 project and using the ubercart module.
When I add product to the shopping cart using uc_cart_add_item() function, the page is redirected to cart page, but I don't want it to redirect to cart page.

Below is the code I used for add to cart.
uc_cart_add_item($nid, 1, NULL, NULL, NULL, $check_redirect = FALSE);

But it is redirected to cart page When I execute the above code.

Same for remove product also, i.e uc_cart_remove_item($nid, $cart_id, array('module' => 'uc_product'));

Any body know the solution please help me.