把数据存储到数据库表中(5)

最后,我们需要修改nodeapi钩子中代码,这样,如果已经存在了一个注释,那么它将被从数据库中取出,并用来预先填充我们的表单。在我们把我们的表单分配给$node->content的代码前面,我们添加以下代码,这里用粗体将其标出了:

 
/**
* Implementation of hook_nodeapi().
*/
function annotate_nodeapi(&$node, $op, $teaser, $page) {
    global $user;
    switch ($op) {
        // The 'view' operation means the node is about to be displayed.
        case 'view':
            // Abort if the user is an anonymous user (not logged in) or
            // if only the node summary (teaser) is being displayed.
            if ($user->uid == 0 || !$page) {
                break;
            }
            // Find out which node types we should annotate.
            $types_to_annotate = variable_get('annotate_node_types', array('page'));
 
            // Abort if this node is not one of the types we should annotate.
            if (!in_array($node->type, $types_to_annotate)) {
                break;
            }
 
           // Get the current annotation for this node from the database
           // and store it in the node object.
           $result = db_query('SELECT note FROM {annotations} WHERE nid = %d
               AND uid = %d', $node->nid, $user->uid);
           $node->annotation = db_result($result);
 
            // Add our form as a content item.
            $node->content['annotation_form'] = array(
                '#value' => drupal_get_form('annotate_entry_form', $node),
                '#weight' => 10
            );
            break;
 
        case 'delete':
            db_query('DELETE FROM {annotations} WHERE nid = %d', $node->nid);
            break;
    }
}
 
 我们首先查询数据库以取回这个用户对这个节点所做的注释。接着,我们使用了db_result(),这个函数是用来从结果集中取出第一条记录的第一个字段。由于我们仅允许一个用户对同一节点只能做一个注释,所以结果集中也只有一行记录。
 
    我们还在nodeapi钩子中的delete操作下添加了逻辑代码,这样当一个节点被删除时,该节点上的所有注释也都将被删除。
 

  测试一下你的模块。它现在应该能够保存和取回注释了。现在可以喘口气了---你已经从头创建了一个模块。在通往Drupal专业开发者的道路上,你已经迈出了关键的一步。

老葛的Drupal培训班 Think in Drupal

Drupal版本: