duanaixuan7385 2017-05-05 06:52
浏览 22
已采纳

Drupal以编程方式使用body创建节点

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?

  • 写回答

3条回答 默认 最新

  • dtw52353 2017-05-05 10:09
    关注

    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();
    

    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'));  
    

    can be replaced with

    $entity = new stdClass();
    $entity->type = 'article';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 收一个快手协议下单算法
  • ¥15 求一个图片中的成交量选股公式
  • ¥15 已知正方形内随机生成坐标matlab
  • ¥30 关于#python#的问题:我想要的是这79个大特征对于房屋售价的最大的影响前十名(相关搜索:随机森林)
  • ¥15 使用matlab计算自定义特殊函数的二重积分,改变积分顺序所得的结果不同的问题?
  • ¥15 mysql做碎片化处理老是报错怎么办
  • ¥15 如何正确在vs2010中初始化map对象
  • ¥30 mmdet3d模型部署问题
  • ¥15 comsol仿真反射率、吸收率时峰值位置和深度不对!
  • ¥30 Visual Studio找不到sdk,如何解决?