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

cha*_*pka 10 php drupal drupal-8

我正在Drupal 8中设计一个新模块.这是一个长期项目,至少几个月内不会上市,所以我用它来弄清楚什么是新的.

在这个模块中,我希望能够以编程方式创建节点.在Drupal 7中,我会通过创建对象,然后调用"node_submit"和"node_save"来完成此操作.

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

我想要做的是基于不是直接从用户呈现的表单中获取的信息,以编程方式创建至少一个并且可能多个新节点.我需要能够:

1)指定内容类型

2)指定URL路径

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

4)提交新节点对象

我希望能够在一个独立的,高度抽象的函数中完成此操作,而不依赖于特定的块或形式.

那我错过了什么?

小智 16

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();
Run Code Online (Sandbox Code Playgroud)


Dav*_*man 5

Devel/devel_generate模块的D8版本有一个很好的例子.

来自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);
Run Code Online (Sandbox Code Playgroud)

使用格式化文本

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

使用以下方法搜索Drupal核心代码:

$ cd drupal/core
$ grep -B 5 -A 5 -r entity_create.*node * > /tmp/temp-grep.txt
Run Code Online (Sandbox Code Playgroud)

然后,在文本编辑器中打开/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',
--
Run Code Online (Sandbox Code Playgroud)

注意'body'现在变成了一个带有'value'和'format'的数组.


Tre*_*rey 5

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

这是不使用功能的简短用法示例。这对于动态创建特别有用:

//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();
Run Code Online (Sandbox Code Playgroud)

  • 自本文编写以来,还有一些内容已被弃用或更改: \Drupal::entityManager() 应该变为 \Drupal::service('entity.manager') https://www.drupal.org/node/2721791;并且 $entity_def-&gt;get() 应该变成 $entity_def-&gt;getKey()。理想情况下,如果您以表单形式执行此操作,则应避免直接访问 \Drupal,并使用依赖项注入:https://code.tutsplus.com/tutorials/drupal-8-properly-injecting-dependency-using- di--cms-26314 (2认同)

cha*_*pka 2

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

$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();
Run Code Online (Sandbox Code Playgroud)

  • 根据文档,entity_create 已被弃用:Drupal 8.0.x 中的 @deprecated,将在 Drupal 9.0.0 之前删除。使用覆盖实体类型的 Entity::create() 方法,例如,如果实体类型已知,则使用 \Drupal\node\Entity\Node::create() 。如果实体类型是可变的,则使用实体存储的create()方法构造一个新实体:请参阅http://drupal.stackexchange.com/a/108874/1895 (2认同)