function nodeapi_example_node_update

Implements hook_node_update().

As an existing node is being updated in the database, we need to do our own database updates.

This hook is called when an existing node has been changed. We can't simply update, since the node may not have a rating saved, thus no database field. So we first check the database for a rating. If there is one, we update it. Otherwise, we call nodeapi_example_node_insert() to create one.

Related topics

File

nodeapi_example/nodeapi_example.module, line 191

Code

function nodeapi_example_node_update($node) {
    if (variable_get('nodeapi_example_node_type_' . $node->type, FALSE)) {
        // Check first if this node has a saved rating.
        $rating = db_select('nodeapi_example', 'e')->fields('e', array(
            'rating',
        ))
            ->where('e.vid = (:vid)', array(
            ':vid' => $node->vid,
        ))
            ->execute()
            ->fetchField();
        if ($rating) {
            // Node has been rated before.
            db_update('nodeapi_example')->fields(array(
                'rating' => $node->nodeapi_example_rating,
            ))
                ->condition('vid', $node->vid)
                ->execute();
        }
        else {
            // Node was not previously rated, so insert a new rating in database.
            nodeapi_example_node_insert($node);
        }
    }
}