Skip directly to content

Adding Items to cart in Drupal Ubercart: uc_cart_add_item() API

on Wed, 02/10/2010 - 07:25

Drupal with Ubercart

 Ubercart is an open source e-commerce package that works on Drupal. It is powerful because it has the flexible archtecture of Drupal behind it.

 Drupal is a powerful web-based, flexible, community solution and with Ubercart at hand, it allows e-commerce functions readily available to Drupal.

 

Ubercart API: uc_cart_add_item()

Ubercart has an interesting API: uc_cart_add_item(). Usually by default, the items are added to the cart when we click on "add to cart" button on the product page. But, this API allows us to add items to the Ubercart's cart as follows:

uc_cart_add_item($nid, $quantity);

Above $nid is the node id of the product you are trying to add to the cart and $quantity is the number of products you would like added.

If your product has attributes as well associated with it that you want to add to your Ubercart's cart

$aid = 'First Attribute Title';
$oid = 'First attribute.';
$data = array( 'attributes' => array( $aid => $oid  ) );
uc_cart_add_item($nid, $qty, $data);

I assume the above makes perfect sense and is quite helpful when we are playing on the Ubercart product node and are performing a custom change where the products are added to the cart. Using above API, we can also add products to the cart when executing some form like during registration, login.

From ActionScript 3?

Would it be possible to utilize this API from flash?  Maybe using amfphp...

If you can call your php code from flash, then you can call this API

If you can call your php code from flash, then you can call this API. But you would to invoke drupal before that. And the way I typically do that is using following code in the php file (say, updatecart.php) before using :

 //call drupal 

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

//now call the API:
$aid = 'First Attribute Title';
$oid = 'First attribute.';
$data = array( 'attributes' => array( $aid => $oid  ) );
uc_cart_add_item($nid, $qty, $data);

how i would do it

I would implement a new url using drupals menu hook...and let this url have parameters like nid and qty, then do a silent get to this url using the appropriate parameters

CAnt fin in API

why isnt this funtion listed in the API