I'm trying to create a rule to populate a multiple value order reference field in Drupal Commerce, on checkout complete.
I haven't been able to achieve this through Rules UI, so instead I'm trying to programmatically create the action but can't figure out how to set the actual value.
I simply want to add a reference of the newly created order to the purchased product, while keeping the references already set (in this particular case an order will never contain more than one product).
I have added an order_reference_field (Commerce Order Reference module) to my product, showing checkboxes with multiple values allowed.
Below my code:
function example_rules_action_info() {
$actions = array();
$actions['commerce_set_product_order_ref'] = array(
'label' => t('Link an order to the purchased product'),
'group' => t('Custom action'),
'parameter' => array(
'commerce_line_item' => array(
'type' => 'commerce_line_item',
'label' => t('Line item'),
),
),
);
return $actions;
}
function commerce_set_product_order_ref($line_item, $order) {
if (in_array($line_item->type, commerce_product_line_item_types())) {
$sku = $line_item->line_item_label;
$product = commerce_product_load_by_sku($sku);
$orderID = $line_item->order_id;
$wrapper = entity_metadata_wrapper('commerce_product', $product);
$wrapper->field_order_reference /***** What to do here? *******/
$result = $wrapper->save();
}
}
EDIT:
I have gotten a little further with the code below.. It works the first time an order reference is set, but the second time i get the following error "The website encountered an unexpected error. Please try again later."
Found the example a bit down this page: https://drupal.org/node/1021556
function example_rules_action_info() {
$actions = array();
$actions['commerce_set_product_order_ref'] = array(
'label' => t('Link an order to the purchased Product'),
'group' => t('Custom action'),
'parameter' => array(
'commerce_line_item' => array(
'type' => 'commerce_line_item',
'label' => t('Line item'),
),
),
);
return $actions;
}
function commerce_set_product_order_ref($line_item, $order) {
if (in_array($line_item->type, commerce_product_line_item_types())) {
$sku = $line_item->line_item_label;
$product = commerce_product_load_by_sku($sku);
$orderID = $line_item->order_id;
$wrapper = entity_metadata_wrapper('commerce_product', $product);
$curr_list = $wrapper->field_order_reference->value();
if (!$curr_list){
$curr_list = array();
}
$curr_list[] = $orderID;
$wrapper->field_order_reference->set($curr_list);
$result = $wrapper->save();
}
}