2017-05-05 119 views
0

我想在使用PHP腳本的Drupal 7中創建節點然後使用Drush執行。Drupal以編程方式創建節點與身體

雖然我能夠用標題創建基本節點,但由於某種原因,我無法設置正文。

我嘗試了兩種不同的方法,使用了我在其他論壇上發現的不同建議。

在第一種情況下,直接設置節點元素:

... 
$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); 

而在這兩種情況下,我都得到一個新的節點發布,但身體永遠不會被設置或顯示。

如何正確設置我正在保存的新節點的正文?

回答

1

若要使用包裝一個節點(需要實體模塊)嘗試下面的代碼:

$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)(需要節點 - >類型),其中規定了一些默認值(正在啓用註釋,是提升到首頁的節點,設置作者,...),因此這些方法之間存在差異。

$entity = entity_create($entity_type, array('type' => 'article')); 

可以

$entity = new stdClass(); 
$entity->type = 'article'; 
+0

我沒有使用「entity_create」,我使用了「新的stdClass」(這不是一個完整的例子),我會試一試,然後看看。 – aaa90210

+0

據此編輯帖子。 – Xilis

0

我在這裏看到

  1. 兩個問題語言
  2. 捆綁式

如果它是一個新的節點使用LANGUAGE_NONE或您的網站的語言。

對於新對象$節點 - >語言將是空的,你會得到通知:

公告:未定義的屬性:stdClass的:: $語言

此代碼的工作對我來說:

$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打印(),並看看你的領域,可能與節點輸出的問題。

+0

耶即時通訊做這一切...它不是一個完整的例子來代替......問題是身體永遠不會出現。 – aaa90210

0

同意Сергей,只是想補充一點,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); 

然後設置其他值,標題,正文...

+0

是啊即時通訊所做的一切......它不是一個完整的例子......問題是身體永遠不會出現。 – aaa90210

+0

嘗試加載和打印某些現有文章的對象(在後端創建)以查看確切的節點對象結構。 – MilanG

+0

這不是一個壞主意...... – aaa90210

相關問題