I am trying to figure out what's the problem with my code. It creates the product, but the price field is allways empty.

$cp = commerce_product_new('deposit_temp_'.$_POST['importe']);
$cp->is_new = TRUE;
$cp->revision_id = NULL;
$cp->status = 1;
$cp->created = $cp->changed = time();
$cp->sku = 'deposit_temp_'.$_POST['importe'];
$cp->title = t('Booking deposit');
$cp->language = LANGUAGE_NONE;
$cp->commerce_price['und'][0]['amount'] = 20;
$cp->commerce_price['und'][0]['currency_code'] = commerce_default_currency();


The price/amount is wrong. You do not have enough significant digits. Commerce works via a base price. Example:

A product that costs $20.00 (USD) is expressed as 2000 in Commerce. Basically all prices in Commerce should have the decimal point moved to the right by two or essentially multiplied by 100 and remove all significant digits to the right of the decimal point.

So in your case the price should be 2000 not 20.

Also I would like to point out a security issue in your code. You are consuming a $_POST global variable directly into Drupal without first cleansing the $_POST. This could open your site up to XSS attacks. You should first past the $_POST global variable through filter_xss() before using the contents of that global variable. Also note that Drupal Core offers ways to consume post variables if you use hook_menu for the page that this is running on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.