You are here

function recipe_save_ingredients in Recipe 7

Same name and namespace in other branches
  1. 5 recipe.module \recipe_save_ingredients()
  2. 6 recipe.module \recipe_save_ingredients()

Saves the ingredients of a recipe node to the database.

Parameters

$node: A node containing an ingredient list.

2 calls to recipe_save_ingredients()
recipe_insert in ./recipe.module
Implements hook_insert().
recipe_update in ./recipe.module
Implements hook_update().

File

./recipe.module, line 231
Contains functions for Recipe node CRUD and display.

Code

function recipe_save_ingredients($node) {
  if (!$node->recipe_ingredients['ing']) {
    $node->recipe_ingredients['ing'] = array();
  }
  foreach ($node->recipe_ingredients['ing'] as $key => $ingredient) {

    // Delete, if you have a valid ri_id and the ingredient name is blank.
    if (isset($ingredient['ri_id']) && empty($ingredient['name'])) {
      db_delete('recipe_node_ingredient')
        ->condition('id', $ingredient['ri_id'])
        ->execute();
    }
    elseif (isset($ingredient['ri_id']) && $ingredient['name'] != '') {
      $ingredient['id'] = recipe_ingredient_id_from_name($ingredient['name']);

      // You have to round it because an indefinite remainder will overflow the normal mysql float type.
      $ingredient['quantity'] = round(recipe_ingredient_quantity_from_fraction($ingredient['quantity']), 6);
      db_update('recipe_node_ingredient')
        ->fields(array(
        'ingredient_id' => $ingredient['id'],
        'quantity' => $ingredient['quantity'],
        'unit_key' => $ingredient['unit_key'],
        'weight' => $ingredient['weight'],
        'note' => $ingredient['note'],
      ))
        ->condition('id', $ingredient['ri_id'])
        ->execute();
    }
    elseif (!isset($ingredient['ri_id']) && $ingredient['name'] != '') {
      $ingredient['id'] = recipe_ingredient_id_from_name($ingredient['name']);

      // You have to round it because an indefinite remainder will overflow the normal mysql float type.
      $ingredient['quantity'] = round(recipe_ingredient_quantity_from_fraction($ingredient['quantity']), 6);
      db_insert('recipe_node_ingredient')
        ->fields(array(
        'nid' => $node->nid,
        'ingredient_id' => $ingredient['id'],
        'quantity' => $ingredient['quantity'],
        'unit_key' => $ingredient['unit_key'],
        'weight' => $ingredient['weight'],
        'note' => $ingredient['note'],
      ))
        ->execute();
    }
  }
}