You are here

function nodeorder_add_node_to_list in Node Order 7

Push new or newly orderable node to top of ordered list.

2 calls to nodeorder_add_node_to_list()
nodeorder_node_insert in ./nodeorder.module
Implements hook_node_insert().
nodeorder_node_update in ./nodeorder.module
Implements hook_node_update().

File

./nodeorder.module, line 828
Nodeorder module.

Code

function nodeorder_add_node_to_list($node, $tid) {

  // Append new orderable node.
  $weights = nodeorder_get_term_min_max($tid);

  // Get the cached weights.
  $query = db_update('taxonomy_index')
    ->fields(array(
    'weight' => $weights['min'] - 1,
  ))
    ->condition('nid', $node->nid)
    ->condition('tid', $tid)
    ->execute();

  // If new node out of range, push top nodes down filling the order gap
  // this is when old list's min weight is top range
  // except when new orderable node increases range (new list is not even).
  $taxonomy_nids = taxonomy_select_nodes($tid, FALSE, FALSE, array(
    't.weight' => 'ASC',
  ));
  $new_node_out_of_range = count($taxonomy_nids) % 2 == 0 && $weights['min'] == -ceil(count($taxonomy_nids) / 2);
  if ($new_node_out_of_range) {

    // Collect top nodes.
    // Note that while the node data is not yet updated in the database, the taxonomy is.
    $top_range_nids = array();
    $previous_weight = $weights['min'] - 2;
    foreach ($taxonomy_nids as $taxonomy_nid) {
      $taxonomy_node_weight = db_select('taxonomy_index', 'i')
        ->fields('i', array(
        'weight',
      ))
        ->condition('tid', $tid)
        ->condition('nid', $taxonomy_nid)
        ->execute()
        ->fetchField();
      if ($taxonomy_node_weight > $previous_weight + 1) {
        break;
      }
      $previous_weight = $taxonomy_node_weight;
      $top_range_nids[] = $taxonomy_nid;
    }
    if (!empty($top_range_nids)) {

      // Move top nodes down.
      $query = db_update('taxonomy_index');
      $query
        ->expression('weight', 'weight + 1');
      $query
        ->condition('nid', $top_range_nids, 'IN')
        ->condition('tid', $tid)
        ->execute();
    }
  }

  // Make sure the weight cache is invalidated.
  nodeorder_get_term_min_max($tid, TRUE);
}