function commerce_coupon_update_7004 in Commerce Coupon 7
Implements hook_update_N(). Embrace EntityReference module.
File
- ./
commerce_coupon.install, line 206 - Install, update and uninstall functions for the commerce_coupon module.
Code
function commerce_coupon_update_7004(&$sandbox) {
$query = new EntityFieldQuery();
$result = $query
->entityCondition('entity_type', 'commerce_line_item')
->propertyCondition('type', 'commerce_coupon')
->execute();
// Get all line items from the system.
$line_items = commerce_line_item_load_multiple(array_keys($result['commerce_line_item']));
// Store an array with the line item id and the coupon id.
$values = array();
foreach ($line_items as $line_item) {
$value = array(
'line_item_id' => $line_item->line_item_id,
'coupon_id' => $line_item->commerce_coupon_reference[LANGUAGE_NONE][0]['coupon_id'],
);
$values[] = $value;
}
// Remove old field and force a new creation, no way to rename it.
// see http://drupal.org/node/1201898
field_delete_field('commerce_coupon_reference');
commerce_coupon_line_item_configuration();
// Finally restore the line item values.
foreach ($values as $value) {
$line_item = commerce_line_item_load($value['line_item_id']);
$line_item->commerce_coupon_reference[LANGUAGE_NONE][0]['target_id'] = $value['coupon_id'];
commerce_line_item_save($line_item);
}
// Also add the coupon reference field to the order.
commerce_coupon_order_configuration();
// Migrate all coupon log references to the field in the order.
$logs = db_query('SELECT * FROM {commerce_coupon_log}')
->fetchAllAssoc('log_id', PDO::FETCH_ASSOC);
foreach ($logs as $log) {
if ($order = commerce_order_load($log['order_id'])) {
$order->commerce_coupon_order_reference[LANGUAGE_NONE][]['target_id'] = $log['coupon_id'];
commerce_order_save($order);
}
}
// Delete the coupon log fields.
commerce_delete_instances('commerce_coupon_log');
// Delete the coupon log database table.
db_drop_table('commerce_coupon_log');
}