03 328 8646

Blog

Adding products and product displays in Drupal Commerce

We have a csv feed available from a POS. It's very limited and doesn't provide sufficient information to put products directly on the site, but it does at least give names, stock levels, skus and a supplier code so it's better than starting from scratch when manually editing. If you have a data feed you want to push into drupal commerce this is an example. Just write some better error handling code and add/remove the fields that do/don't exist in your set up.

Entity wrappers make this a nice easy job once you know the fields you're populating. If you're reading this and would like the rest of the import module as an example just get in touch.

function snappy_function_name_goes_here($sku, $price, $stock, $supplier_code, $title) {
  /*
   * Create a product entity and then a node that relates to it
   *  if the product exists and we got here by mistake log it and just move on 
   *    - this should have been caught before entering this code so an update runs instead of a create new
   */

  try {
    //Create product
    $p_wrapper = entity_metadata_wrapper('commerce_product', commerce_product_new('food'));
    $p_wrapper->title = check_plain($title);
    $p_wrapper->sku = check_plain($sku);
    $p_wrapper->commerce_price->amount = $price; // this already arrives as cents eg 3799 and not 37.99
    $p_wrapper->commerce_price->currency_code = variable_get('commerce_default_currency', 'NZD'); // should be available from the standard install 
    if ($default_tax = variable_get('commerce_default_tax_rate_default')) {
      //this site uses the Default Tax Rate module so we can use the default rate as nothing is available in the feed
      // https://www.drupal.org/project/commerce_default_tax_rate
      $p_wrapper->commerce_price->data = array('include_tax' => $default_tax);
    }
    $p_wrapper->field_supplier_product_code = check_plain($supplier_code);
    $p_wrapper->commerce_stock = check_plain($stock);
    $p_wrapper->save();
    $p_id = $p_wrapper->getIdentifier();;

    // create node and set the product reference field to the entity created above
    $n_wrapper = entity_metadata_wrapper('node', commerce_product_new('food'));
    $n_wrapper->title = check_plain($title);
    $n_wrapper->status = 0; // No image, no description etc, don't publish this node.
    $n_wrapper->field_product[] = $p_id; // field_product is a mult-value field so use []
    $n_wrapper->save();

  }
  catch (EntityMetadataWrapperException $exc) {
      watchdog(
        'hc_csv_stock_update',
        'See '  . __FUNCTION__ . '() ' .  $exc->getTraceAsString(),
         NULL, WATCHDOG_ERROR
      );
  }
}