How to programmatically create a Drupal Commerce product with price

2k Views Asked by At

I am creating a Drupal Commerce product in code using the following:

$cp = commerce_product_new('product');
$cp->is_new = TRUE;
$cp->revision_id = NULL;
$cp->uid = 1;
$cp->status = 1;
$cp->created = $cp->changed = time();
$cp->sku = $product[sku];
$cp->title = $product[name];
$cp->language = LANGUAGE_NONE;
$cp->commerce_price->amount = $product[sale_price] ? $product[sale_price] : $product[retail_price];
$cp->commerce_price->currency_code = 'USD';
commerce_product_save($cp);

If I comment out the two lines pertaining to price, the product gets added, but has no price.

If I do NOT comment out the 2 lines, I get a 500 error

If I change the pricing part to be:

$cp->commerce_price = array(
  'amount' => $product[sale_price] ? $product[sale_price] : $product[retail_price],
  'currency_code' => 'USD',
);

I do not get the 500, but I get the message

Warning: Invalid argument supplied for foreach() in _commerce_price_field_serialize_data() (line 148 of commerce/modules/price/commerce_price.module).

for each product being added, with the result being the products being added and available, but no price information in the field_data_commerce_price table for any of them.

1

There are 1 best solutions below

0
On

Turns out it needs to be:

$cp->commerce_price = array(LANGUAGE_NONE => array( 0 => array(
 'amount' => $product[sale_price] ? $product[sale_price] : $product[retail_price],
 'currency_code' => 'USD',
)));