Belmark Caday
Belmark Caday

Reputation: 1683

How to use nodeapi in drupal?

guys i have this node type -> movie. this movie has casts in it. so now i was instructed to display the number of cast in a movie. how do i achieve this by using nodeapi? please someone guide mo through this. im very new to drupal coding here. here's what ive made so far:

function count_cast_nodeapi(&$node, $op) {
   switch ($op) {
      case 'update index':
         if ($node->type == 'movie') {
            $text = ''; 
            $q = db_query('SELECT count(field_movie_cast_nid) FROM content_field_movie_cast ' .
                          'WHERE nid = %d', $node->nid);
        if ($r = db_fetch_object($q)) {
           $text = $r->count;
        }
        drupal_set_message($text);
        }
    }
}

but i have no idea where to put this code. where to save it. do i make a module of this? and is this code even correct?

also i have only copied this code. so i dont know what that 'update index' means. and who or what function will set that parameter $op

Upvotes: 0

Views: 94

Answers (1)

Vadim Eremeev
Vadim Eremeev

Reputation: 479

I can suggest you follow solution:

  1. Create new integer CCK field for content type "movie" which will store the number of casts. Name it movie_cast_number.
  2. This field will be updating in hook_nodeapi (similar to your example). For that you need to create custom module "count_cast". Place it to sites/all/modules directory.
  3. In hook_nodeapi need to use $op "insert" and "update". $op generating by module node and means which operation is performed with node. Insert means new node has been created and update - existing node has been updated.
  4. If you need custom output for this content type then you need to create node-movie.tpl.php in your theme directory.

Code which update the number of casts can looks follow way:

function count_cast_nodeapi(&$node, $op) {
  switch ($op) {
      case 'update':
      case 'insert':
         if ($node->type == 'movie') {
           $result = db_result(db_query('
             SELECT count(field_movie_cast_nid) cnt
             FROM {content_field_movie_cast}
             WHERE nid = %d
           ', $node->nid));
           $node->field_movie_cast_number[0]['value'] = $result->cnt;
        }
    }
}

Upvotes: 1

Related Questions