function NodeCreationTrait::createNode

Same name and namespace in other branches
  1. 11.x core/modules/node/tests/src/Traits/NodeCreationTrait.php \Drupal\Tests\node\Traits\NodeCreationTrait::createNode()
  2. 10 core/modules/node/tests/src/Traits/NodeCreationTrait.php \Drupal\Tests\node\Traits\NodeCreationTrait::createNode()
  3. 9 core/modules/node/tests/src/Traits/NodeCreationTrait.php \Drupal\Tests\node\Traits\NodeCreationTrait::createNode()

Creates a node based on default settings.

Parameters

array $values: (optional) An associative array of values for the node, as used in creation of entity. Override the defaults by specifying the key and value in the array, for example:

$this->drupalCreateNode(array(
  'title' => t('Hello, world!'),
  'type' => 'article',
));

The following defaults are provided:

  • body: Random string using the default filter format:
$values['body'][0] = array(
  'value' => $this->randomMachineName(32),
  'format' => filter_default_format(),
);
  • title: Random string.
  • type: 'page'.
  • uid: The currently logged in user, or anonymous.

Return value

\Drupal\node\NodeInterface The created node entity.

40 calls to NodeCreationTrait::createNode()
CommentTestBase::setUp in core/modules/comment/src/Tests/Views/CommentTestBase.php
CommentTestBase::setUp in core/modules/comment/src/Tests/CommentTestBase.php
FileFieldTestBase::uploadNodeFiles in core/modules/file/src/Tests/FileFieldTestBase.php
Uploads multiple files to a node.
FormErrorHandlerQuickEditTest::testDisabledInlineFormErrors in core/modules/inline_form_errors/tests/src/FunctionalJavascript/FormErrorHandlerQuickEditTest.php
Tests that the inline form errors are not visible for Quick Edit forms.
GlossaryTest::testGlossaryView in core/modules/views/tests/src/Functional/GlossaryTest.php
Tests the default glossary view.

... See full list

File

core/modules/node/tests/src/Traits/NodeCreationTrait.php, line 69

Class

NodeCreationTrait
Provides methods to create node based on default settings.

Namespace

Drupal\Tests\node\Traits

Code

protected function createNode(array $values = []) {
  // Populate defaults array.
  $values += [
    'body' => [
      [
        'value' => $this->randomMachineName(32),
        'format' => filter_default_format(),
      ],
    ],
    'title' => $this->randomMachineName(8),
    'type' => 'page',
  ];
  if (!array_key_exists('uid', $values)) {
    $user = User::load(\Drupal::currentUser()->id());
    if ($user) {
      $values['uid'] = $user->id();
    }
    elseif (method_exists($this, 'setUpCurrentUser')) {
      /** @var \Drupal\user\UserInterface $user */
      $user = $this->setUpCurrentUser();
      $values['uid'] = $user->id();
    }
    else {
      $values['uid'] = 0;
    }
  }
  $node = Node::create($values);
  $node->save();
  return $node;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.