1

So I know how to go about adding an item to the cart with PHP like this;

$product_nid = 2;
$some_data = NULL;

  uc_cart_empty(uc_cart_get_id());

  $data = serialize($some_data);

  uc_cart_add_item($product_nid, $qty = 1, $data, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE);

but I'm uncertain how to add a product with a certain attribute/option such as if I have product "A" with options "1" and "2" I was hoping I could get a little help. This is for Drupal 7, Ubercart 3.

  • figured it out, perhaps this will be of help for someone :) – chris Feb 9 '14 at 23:40
  • $product_nid = 2; $some_data = array( 'attributes' => array( '1' => '1', ), ); uc_cart_empty(uc_cart_get_id()); $data = serialize($some_data); uc_cart_add_item($product_nid, $qty = 1, $data, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE); – chris Feb 9 '14 at 23:40
  • 1
    Both answers are wrong. $data should not be serialized. – David Mar 3 '15 at 1:29
2

Taking Chris's answer an putting it in Answer format for readability.

Figured it out, perhaps this will be of help for someone :)

$product_nid = 2;  
$some_data = array('attributes' => array( 
                   '1' => '1', 
                  ),
             );
uc_cart_empty(uc_cart_get_id());
$data = serialize($some_data);
uc_cart_add_item($product_nid, 
                 $qty = 1,
                 $data,
                 $cid = NULL,
                 $msg = TRUE,
                 $check_redirect = TRUE,
                 $rebuild = TRUE);
  • 1
    I agree with David from the above comment, the $data should not be serialized. – DrCord Mar 4 '15 at 23:25
0

i am using ubercart in drupal 8

$session = \Drupal::service('session');

$cart_manager = \Drupal::service('uc_cart.manager');

$anonymous_cart = $cart_manager->setID($session->get('uc_cart_id'));

$sql="delete from uc_cart_products where cart_id='".$anonymous_cart."'";

db_query($sql);

$result= db_insert('uc_cart_products')

        ->fields(array(
        'cart_id' => $anonymous_cart,
        'nid' => $nid,
        'qty' => $quantity,
        'changed' => strtotime(date('Y-m-d')),
        'data' => ($data),
        ))
        ->execute();
  • Quote from the question: "This is for Drupal 7" ... – Pierre.Vriens Aug 13 '17 at 7:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.