Tried different solutions, now I'm looking for this...

SITUATION
I need to create a custom order via rules (trigger is creation of new node) with a calculated price that references the node. I have a custom field in order settings for this.

My rule looks like:
- Create entity order (with status=checkout/payment)
- Set data value of order's field referencing my node
- Save entity order

This works.
Now I need to add line-items/products to fill the order with a calculated price (based on some fields in the node).

I've tried adding:
- Create entity line-item
- Add item to list (add line-item to order just created)
- Save order again

But "EntityMalformedException: Missing bundle property on entity of type commerce_order." comes out.

QUESTION
How do I add products/line-item to the order setting the price and then redirect user to payment?
Ideally I would like to add a list of products (about three or four) already set in the admin's panel, but customizing their price (and of course the total!)

Comments

Elementica’s picture

I've tried also a single php snippet, like in http://www.commerceguys.com/resources/articles/245 with following code:

$product_id = 1;

// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
$order = commerce_order_new($user->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; // <---- ERROR HERE

// ... and HERE I need to set a custom field of type "reference node" I've
// in order's settings ...

// Save the order again to update its line item reference field.
commerce_order_save($order);

// Redirect to the order's checkout form. Obviously, if this were a
// form submit handler, you'd just set $form_state['redirect'].
drupal_goto('checkout/' . $order->order_id);

... but I get Fatal error: Cannot use object of type EntityDrupalWrapper as array ... at line $order_wrapper->commerce_line_items[] = $line_item; and I need to set one more field (see code above)

Elementica’s picture

Suddenly the error is arising no more! (maybe caching problem?)

Anyway: in configuration -> order settings -> manage fields I've created a custom field "node reference" for orders... how do I set it in the above snippet? It's reached as $order_wrapper->field_noderef...