php 如何在 Drupal 8 中以编程方式创建节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24172791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:11:46  来源:igfitidea点击:

How to programmatically create a node in Drupal 8?

phpdrupaldrupal-8

提问by chapka

I'm designing a new module in Drupal 8. It's a long-term project that won't be going public for a few months at least, so I'm using it as a way to figure out what's new.

我正在 Drupal 8 中设计一个新模块。这是一个长期项目,至少在几个月内不会公开,所以我用它来找出新的内容。

In this module, I want to be able to programmatically create nodes. In Drupal 7, I would do this by creating the object, then calling "node_submit" and "node_save".

在这个模块中,我希望能够以编程方式创建节点。在 Drupal 7 中,我会通过创建对象,然后调用“node_submit”和“node_save”来做到这一点。

These functions no longer exist in Drupal 8. Instead, according to the documentation, "Modules and scripts may programmatically submit nodes using the usual form API pattern." I'm at a loss. What does this mean? I've used Form API to create forms in Drupal 7, but I don't get what the docs are saying here.

这些函数在 Drupal 8 中不再存在。相反,根据文档,“模块和脚本可以使用通常的表单 API 模式以编程方式提交节点。” 我不知所措。这是什么意思?我已经使用 Form API 在 Drupal 7 中创建表单,但我不明白文档在这里说的是什么。

What I'm looking to do is programmatically create at least one and possibly multiple new nodes, based on information not taken directly from a user-presented form. I need to be able to:

我希望做的是根据不是直接从用户呈现的表单中获取的信息,以编程方式创建至少一个,可能还有多个新节点。我需要能够:

1) Specify the content type

1) 指定内容类型

2) Specify the URL path

2)指定网址路径

3) Set any other necessary variables that would previously have been handled by the now-obsolete node_object_prepare()

3) 设置以前由现在已过时的 node_object_prepare() 处理的任何其他必要变量

4) Commit the new node object

4)提交新的节点对象

I would prefer to be able to do this in an independent, highly abstracted function not tied to a specific block or form.

我希望能够在一个独立的、高度抽象的函数中做到这一点,而不依赖于特定的块或形式。

So what am I missing?

那么我错过了什么?

采纳答案by chapka

Figured it out. For anyone else with this issue, nodes are now treated as entities, and the entity module is now part of core. So my code ended up looking like this:

弄清楚了。对于遇到此问题的任何其他人,节点现在被视为实体,实体模块现在是核心的一部分。所以我的代码最终看起来像这样:

$new_page_values = array();
$new_page_values['type'] = 'my_content_type';
$new_page_values['title'] = $form_state['values']['page_title'];
$new_page_values['path'] = $new_page_path;

$new_page = entity_create('node', $new_page_values);
$new_page->save();

回答by Rookie Rod

use Drupal\node\Entity\Node;

$node = Node::create(array(
    'type' => 'your_content_type',
    'title' => 'your title',
    'langcode' => 'en',
    'uid' => '1',
    'status' => 1,
    'field_fields' => array(),
));

$node->save();

回答by Trey

RE: deprecated entity create

RE:不推荐使用的实体创建

Here is a short example of usage without the deprecated functions. This is particularly helpful for dynamic creation:

这是一个没有弃用函数的简短用法示例。这对动态创建特别有帮助:

//define entity type and bundle
$entity_type="node";
$bundle="article";

//get definition of target entity type
$entity_def = \Drupal::entityManager()->getDefinition($entity_type);

//load up an array for creation
$new_node=array(
  //set title
  'title' => 'test node',

  //set body
  'body' => 'this is a test body, can also be set as an array with "value" and "format" as keys I believe',

  //use the entity definition to set the appropriate property for the bundle
  $entity_def->get('entity_keys')['bundle']=>$bundle
);

$new_post = \Drupal::entityManager()->getStorage($entity_type)->create($new_node);
$new_post->save();

回答by David Luhman

The D8 version of devel/devel_generate module has a good example of this.

devel/devel_generate 模块的 D8 版本有一个很好的例子。

From devel_generate:

devel_generate

  $edit_node = array(
    'nid' => NULL, 
    'type' => $node_type, 
    'uid' => $users[array_rand($users)], 
    'revision' => mt_rand(0, 1), 
    'status' => TRUE, 
    'promote' => mt_rand(0, 1), 
    'created' => REQUEST_TIME - mt_rand(0, $results['time_range']), 
    'langcode' => devel_generate_get_langcode($results),
  );
  if ($type->has_title) {
    // We should not use the random function if the value is not random
    if ($results['title_length'] < 2) {
      $edit_node['title'] = devel_create_greeking(1, TRUE);
    }
    else {
      $edit_node['title'] = devel_create_greeking(mt_rand(1, $results['title_length']), TRUE);
    }
  }
  else {
    $edit_node['title'] = '';
  }
  // @todo Remove once comment become field. http://drupal.org/node/731724
  if (Drupal::moduleHandler()->moduleExists('comment')) {
    $edit_node['comment'] = variable_get('comment_' . $node_type, COMMENT_NODE_OPEN);
  }
  $node = entity_create('node', $edit_node);

Using formatted text

使用格式化文本

Using grep with before/after code lines helped me figure out how to add a node with 'full_html'.

在代码行之前/之后使用 grep 帮助我弄清楚如何使用“full_html”添加节点。

Search the Drupal core code with this :

使用以下命令搜索 Drupal 核心代码:

$ cd drupal/core
$ grep -B 5 -A 5 -r entity_create.*node * > /tmp/temp-grep.txt

Then, open up /tmp/temp-grep.txt in a text editor. Poke around there a bit and you'll see this :

然后,在文本编辑器中打开 /tmp/temp-grep.txt。在那里戳一下,你会看到这个:

--
modules/editor/src/Tests/EditorFileUsageTest.php-    $body_value .= '<img src="awesome-llama.jpg" data-editor-file-uuid="invalid-editor-file-uuid-value" />';
modules/editor/src/Tests/EditorFileUsageTest.php-    // Test handling of a non-existing UUID.
modules/editor/src/Tests/EditorFileUsageTest.php-    $body_value .= '<img src="awesome-llama.jpg" data-editor-file-uuid="30aac704-ba2c-40fc-b609-9ed121aa90f4" />';
modules/editor/src/Tests/EditorFileUsageTest.php-    // Test editor_entity_insert(): increment.
modules/editor/src/Tests/EditorFileUsageTest.php-    $this->createUser();
modules/editor/src/Tests/EditorFileUsageTest.php:    $node = entity_create('node', array(
modules/editor/src/Tests/EditorFileUsageTest.php-      'type' => 'page',
modules/editor/src/Tests/EditorFileUsageTest.php-      'title' => 'test',
modules/editor/src/Tests/EditorFileUsageTest.php-      'body' => array(
modules/editor/src/Tests/EditorFileUsageTest.php-        'value' => $body_value,
modules/editor/src/Tests/EditorFileUsageTest.php-        'format' => 'filtered_html',
--

Note how 'body' now becomes an array with a 'value' and a 'format'.

请注意“body”现在如何变成一个带有“value”和“format”的数组。

回答by Vernit Gupta

Best way to create node in Drupal 8 via using core services

通过使用核心服务在 Drupal 8 中创建节点的最佳方式

$node = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type'       => 'content_type_machine_name',
  'field_text' => 'Foo',
  'title'      => 'Text Title',
]);
$node->save();