如何在Drupal中的Cron作业中创建节点?
时间:2020-03-06 14:19:22 来源:igfitidea点击:
在drupal 4.7的自定义模块中,我将一个节点对象砍在一起,并将其传递给node_save($ node)来创建节点。该hack似乎在drupal 6中不再起作用。虽然我确定可以修复此hack,但我很好奇是否存在标准的解决方案来创建不带表单的节点。在这种情况下,数据是从另一个网站上的自定义提要中提取的。
解决方案
我不知道用于实用地创建节点的标准API。但这就是我从构建一个可以执行我们要执行的操作的模块中收集到的。
- 确保设置了重要字段:uid,名称,类型,语言,标题,正文,过滤器(请参阅" node_add()"和" node_form()")
- 通过
node_object_prepare()
传递节点,以便其他模块可以添加到$ node对象中。
实现此目标的最佳实践方法是利用drupal_execute。 drupal_execute将运行标准验证和基本节点操作,从而使事情按系统预期的方式运行。 drupal_execute具有其怪癖,并且比简单的node_save直观性要差,但是,在Drupal 6中,我们可以按以下方式使用drupal_execute。
$form_id = 'xxxx_node_form'; // where xxxx is the node type $form_state = array(); $form_state['values']['type'] = 'xxxx'; // same as above $form_state['values']['title'] = 'My Node Title'; // ... repeat for all fields that you need to save // this is required to get node form submits to work correctly $form_state['submit_handlers'] = array('node_form_submit'); $node = new stdClass(); // I don't believe anything is required here, though // fields did seem to be required in D5 drupal_execute($form_id, $form_state, $node);
我发现的另一个答案是使用drupal核心中的blogapi模块中的示例。它处于核心地位这一事实使我更有信心,它将在将来的版本中继续使用。
上面有一些很好的答案,但是在将摄取的提要项转换为节点的特定示例中,我们还可以采用使用simplefeed模块的方法(http://wwww.drupal.org/project/simplefeed)。该模块使用simplepie引擎来提取提要,并将每个提要中的单个项目转换为节点。我意识到这并没有专门解决从cron创建节点的问题,但它可能是解决我们总体问题的一种更简单的方法。
node_save()在Drupal 6中仍然可以正常工作;我们需要准备一些特定的数据才能使其正常工作。
$node = new stdClass(); $node->type = 'story'; $node->title = 'This is a title'; $node->body = 'This is the body.'; $node->teaser = 'This is the teaser.'; $node->uid = 1; $node->status = 1; $node->promote = 1; node_save($node);
"状态"和"升级"很容易忽略-如果未设置,则该节点将保持未发布和升级状态,并且只有进入内容管理屏幕时才能看到。