Drupal e Ubercart: creare un prodotto-kit personalizzato via codice PHP
Per lavoro mi sono imbattuto in questa situazione: gestire un prodotto-kit in un carrello e-commerce gestito esternamente da ubercart.
In pratica ho il mio negozio con tutti i prodotti standard. Il mio intento è quello di creare un nuovo prodotto-kit come composizione di altri prodotti già presenti nel negozio… ma questo via codice e non lato form admin.
Per riuscire in questo intento ho dovuto mettere mano al codice PHP e gestire una serie di cose.
Il codice seguente eseguirà alcune operazioni: creazione di un nodo drupal di tipo prodotto kit, impostazione di alcuni parametri ed aggiornamento vari dello stesso ed infine l’aggiunta al carrello dell’utente attuale.
Eccolo riportato di seguito:
// Create an object to fill the overall needed information, like type and more...
$node = (object) array();
global $user;
$account = user_load(array('uid' => $user->uid));
// WARNING: this not work properly... I've seen that uid is always set to "0"... why?
$node->uid = $account->uid;
// Specify that the new node is a product-kit node
$node->type = "product_kit";
$node->status = 1;
$node->promote = 0;
$node->sticky = 0;
$node->revision = 0;
$node->language = "";
$node->title = "Title of product-kit";
$node->body = "Body as Lorem Ipsum and so on...";
$node->teaser = "";
$file_drupal_path = "physical path of image";
$file = new stdClass();
$file->filename = basename($file_drupal_path);
$file->filepath = $file_drupal_path;
$file->filemime = mime_content_type($file_drupal_path);
$file->filesize = filesize($file_drupal_path);
$file->uid = $user->uid;
$file->timestamp = time();
drupal_write_record('files', $file);
$node->field_image_cache[0] = field_file_load($file->fid);
// In my case, 38 is a taxonomy categories
$node->taxonomy = array(38);
// 459 and 460, for example, are the two products that make up the entire product-kit
$node->products = array(459, 460);
// Ok, this is not too beautiful to see... but the lines represent the external products and the relative quantities (1 and 3)
$node->items[459]["qty"] = 1;
$node->items[460]["qty"] = 3;
node_submit($node);
node_save($node);
// Update the product-kit information
uc_product_kit_update($node);
// This statement adds the new product-kit to the current user cart automatically
uc_cart_add_item($node->nid);
