Drupal通过身体创建节点 [英] Drupal create node with body programmatically
问题描述
我试图使用PHP脚本在Drupal 7中创建节点,然后使用Drush执行.
I am trying to create nodes in Drupal 7 using a php script I then execute using Drush.
虽然我可以创建带有标题的基本节点,但由于某些原因,我无法设置主体.
While I am able to create a basic node with a title, I am not able to set the body for some reason.
我尝试了使用其他论坛上提供的不同建议的两种不同方法.
I have tried two different approaches using different advice I found on other forums.
在第一种情况下,直接设置节点元素:
In the first case, setting node elements directly:
...
$node->title = 'Your node title';
$node->body[$node->language][0]['value'] = "<p>this is a test</p>";
$node->body[$node->language][0]['summary'] = "body summary;
$node->body[$node->language][0]['format'] = 'full_html';
在第二种情况下,使用实体包装:
In the second cases, using Entity Wrappers:
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->body->set(array('value' => '<p>New content</p>', 'format' => 'full_html'));
在两种情况下,我都按如下方式保存节点:
In both cases I am saving the node like follows:
$node = node_submit($node);
node_save($node);
在这两种情况下,我都发布了一个新节点,但是主体从未设置或显示.
And in both cases I get a new node published, but the body never gets set or displays.
如何正确设置要保存的新节点的主体?
How do I correctly set the body of a new node I am saving?
推荐答案
要使用包装器创建节点(需要实体模块),请尝试以下代码:
To create a node using a wrapper (requires entity module) try the code below:
$entity_type = 'node';
$entity = entity_create($entity_type, array('type' => 'article'));
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->title = 'title';
$wrapper->body->value = 'body value';
$wrapper->body->summary = 'summary';
$wrapper->body->format = 'full_html';
$wrapper->save();
在СергейФилимонов的示例中,他没有调用node_object_prepare($node)
(需要node-> type),后者设置了一些默认值(启用注释,是将节点升级到首页,还是设置作者,...) ,因此这两种方法之间存在差异.
In Сергей Филимонов's example, he doesn't call node_object_prepare($node)
(requires node->type), which sets some defaults (is commenting enabled, is the node promoted to the front page, sets the author, ...), so there are differences between the approaches.
$entity = entity_create($entity_type, array('type' => 'article'));
可以替换为
$entity = new stdClass();
$entity->type = 'article';
这篇关于Drupal通过身体创建节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!