[英]Drupal create node with body programmatically
我試圖使用PHP腳本在Drupal 7中創建節點,然后使用Drush執行。
雖然我可以創建帶有標題的基本節點,但是由於某些原因,我無法設置主體。
我在其他論壇上找到了不同的建議,嘗試了兩種不同的方法。
在第一種情況下,直接設置節點元素:
...
$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';
在第二種情況下,使用實體包裝器:
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->body->set(array('value' => '<p>New content</p>', 'format' => 'full_html'));
在這兩種情況下,我都按如下方式保存節點:
$node = node_submit($node);
node_save($node);
在這兩種情況下,我都會發布一個新節點,但是主體永遠不會設置或顯示。
如何正確設置要保存的新節點的主體?
要使用包裝器(需要實體模塊)創建節點,請嘗試以下代碼:
$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),后者設置了一些默認值(啟用注釋,該節點被提升到首頁,設置作者,...),因此這兩種方法之間存在差異。
$entity = entity_create($entity_type, array('type' => 'article'));
可以替換為
$entity = new stdClass();
$entity->type = 'article';
我在這里看到兩個問題
如果是新節點,請使用LANGUAGE_NONE或您的站點語言。
對於新對象$ node-> language將為空,您將得到通知:
注意:未定義的屬性:stdClass :: $ language
該代碼對我有用:
$node = new stdClass();
$node->title = 'Your node title';
$node->type = 'article';
$node->language = LANGUAGE_NONE;
$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';
$node = node_submit($node);
node_save($node);
始終在此處$ node-> type設置正確的節點捆綁類型。 它是節點內容類型的機器名稱。
因此,轉到管理/內容頁面,並查看帶有新節點的行:
但是,您可以嘗試使用node_load()函數加載節點,使用var_dump()打印它,並查看您的字段,這可能是節點輸出的問題。
同意Сергей並只想添加該node_object_prepare()也應調用:
https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_object_prepare/7.x
$node = new stdClass();
$node->type = 'article';
node_object_prepare($node);
然后設置其他值,標題,正文...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.