在前几节中,我们实现了一个添加annotation(注释)的表单,可是当我们输入注释并点击“更新”按钮时,输入的注释并没有添加到系统中。这一节中我们将学习如何把数据存入/取出数据库。
我们需要存储这几个字段:注释,与该注释对应的node号,提交注释的用户号,提交注释的时间戳。建立一个名为annotate.install的文件,其内容如下:
<?php
// $Id$
/**
* Implementation of hook_install().
*/
function annotate_install() {
// Use schema API to create database table.
drupal_install_schema('annotate');
}
/**
* Implementation of hook_uninstall().
*/
function annotate_uninstall() {
// Use schema API to delete database table.
drupal_uninstall_schema('annotate');
// Delete our module's variable from the variables table.
variable_del('annotate_node_types');
}
/**
* Implementation of hook_schema().
*/
function annotate_schema() {
$schema['annotations'] = array(
'description' => t('Stores node annotations that users write.'),
'fields' => array(
'nid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => t('The {node}.nid to which the annotation applies.')
),
'uid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => t('The {user}.uid of the user who created the annotation.')
),
'note' => array(
'type' => 'text',
'not null' => TRUE,
'size' => 'big',
'description' => t('The text of the annotation.')
),
'created' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => t('A Unix timestamp indicating when the annotaion was created.')
),
),
'primary key' => array(
'nid', 'uid'
),
);
return $schema;
}
友情提示1:这里使用的是variable_del()函数,variable_delete()函数在Drupal6.8中已经没有了
建立了annotations表,并且创建了nid和uid的联合主键。当annotate模块第一次被激活时,Drupal会寻找名为 annotate.install的文件,并运行annotate_install函数来建立需要的表和字段。因为我们已经激活过了annotate模块,要让annotate.install文件起作用,执行以下步骤:
1. 禁用annotate模块
2. 卸载annotate模块
3. 重新激活annotate模块
接下来要对annotate.module文件做些修改,这样才能将提交的注释存入表中。
1. 在文件最后添加如下代码:
/**
* Handle submission of the annotation form and saving
* of the data to the database.
*/
function annotate_entry_form_submit($form, $form_state) {
global $user;
$note = $form_state['values']['note'];
$nid = $form_state['values']['nid'];
db_query('DELETE FROM {annotations} WHERE nid = %d AND uid = %d', $nid, $user->uid);
db_query("INSERT INTO {annotations} (nid, uid, note, created) VALUES (%d, %d, '%s', %d)", $nid, $user->uid, $note, time());
drupal_set_message(t('Your annotation has been saved.'));
}
2. 修改annotate_nodeapi()函数,具体代码见 这里
做完这些后,我们添加的注释就能够从数据库中存入/取出了。
原文:http://www.drupalbar.com/node/109


libo 发表于 2009-02-07 22:31