Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I have a product with a custom field, according to this. I know I can create product with

$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 = array(LANGUAGE_NONE => array( 0 => array(
 'amount' => $product[sale_price] ? $product[sale_price] : $product[retail_price],
 'currency_code' => 'USD',
)));$product[retail_price];
commerce_product_save($cp);

but I have some custom field.

How can I create a Drupal Commerce product programmatically with full custom fields?

Is $cp->myfield1='22'; sufficient?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

A commerce product is an entity like any other, so...

$cp->field_my_field[LANGUAGE_NONE][0]['value'] = '22';
share|improve this answer
    
thanks master ;) –  zhilevan Mar 4 at 14:08

Just a tweak: the create method on the product controller already has some defaults so no need to add things like is_new or status.

  public function create(array $values = array()) {
    $values += array(
      'product_id' => NULL,
      'is_new' => TRUE,
      'sku' => '',
      'revision_id' => NULL,
      'title' => '',
      'uid' => '',
      'status' => 1,
      'created' => '',
      'changed' => '',
    );

    return parent::create($values);
  }

So I'd just do:

$cp = commerce_product_new('product');
$cp->uid = 1;
$cp->sku = $product[sku];
$cp->title = $product[name];
$cp->language = LANGUAGE_NONE;
$cp->commerce_price = array(LANGUAGE_NONE => array( 0 => array(
 'amount' => $product[sale_price] ? $product[sale_price] : $product[retail_price],
 'currency_code' => 'USD',
)));$product[retail_price];
$cp->my_field[LANGUAGE_NONE][0]['value'] = 22;
commerce_product_save($cp);
share|improve this answer
1  
Thanks for your answer, but my code was correct and I achieve it by note that clive mention me, tnx for spend time –  zhilevan May 27 at 11:24
1  
Just left it here in case someone else bumps into this :). You could mark Clive's answer as accepted for clarity. –  pcambra May 27 at 11:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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