I want to add a product to the cart programmatically on form submit
My code below works only for root, but in my site an anonymous user can access the cart and checkout, but when submitting form with non user=1 it returns Your shopping cart is empty
.
In my submit function:
$uid = ($user->uid) ? $user->uid : 0; $order = commerce_order_new($uid, 'checkout_checkout'); // Save the order to get its ID. commerce_order_save($order); // Load whatever product represents the item the customer will be // paying for and create a line item for it. $product = commerce_product_load($product_id); $line_item = commerce_product_line_item_new($product, 1, $order->order_id); // Save the line item to get its ID. commerce_line_item_save($line_item); // Add the line item to the order using fago's rockin' wrapper. $order_wrapper = entity_metadata_wrapper('commerce_order', $order); $order_wrapper->commerce_line_items[] = $line_item; // Save the order again to update its line item reference field. commerce_order_save($order); //commerce_cart_order_refresh($order); // ym(commerce_cart_order_id($uid)); //commerce_cart_commerce_order_load($order); //ym(commerce_cart_order_is_cart($order)); //commerce_cart_product_add($uid, $line_item); //commerce_cart_product_add_by_id($product_id); //$form_state['redirect'] = 'cart'; drupal_goto('cart');
Why does it not work correctly with non root (uid=1)?
Sponsored by SupremePR