3 namespace Drupal\simpletest;
5 use Drupal\node\Entity\Node;
8 * Provides methods to create node based on default settings.
10 * This trait is meant to be used only by test classes.
12 trait NodeCreationTrait {
15 * Get a node from the database based on its title.
17 * @param string|\Drupal\Component\Render\MarkupInterface $title
18 * A node title, usually generated by $this->randomMachineName().
20 * (optional) Whether to reset the entity cache.
22 * @return \Drupal\node\NodeInterface
23 * A node entity matching $title.
25 public function getNodeByTitle($title, $reset = FALSE) {
27 \Drupal::entityTypeManager()->getStorage('node')->resetCache();
29 // Cast MarkupInterface objects to string.
30 $title = (string) $title;
31 $nodes = \Drupal::entityTypeManager()
33 ->loadByProperties(['title' => $title]);
34 // Load the first node returned from the database.
35 $returned_node = reset($nodes);
36 return $returned_node;
40 * Creates a node based on default settings.
42 * @param array $settings
43 * (optional) An associative array of settings for the node, as used in
44 * entity_create(). Override the defaults by specifying the key and value
45 * in the array, for example:
47 * $this->drupalCreateNode(array(
48 * 'title' => t('Hello, world!'),
49 * 'type' => 'article',
52 * The following defaults are provided:
53 * - body: Random string using the default filter format:
55 * $settings['body'][0] = array(
56 * 'value' => $this->randomMachineName(32),
57 * 'format' => filter_default_format(),
60 * - title: Random string.
62 * - uid: The currently logged in user, or anonymous.
64 * @return \Drupal\node\NodeInterface
65 * The created node entity.
67 protected function createNode(array $settings = []) {
68 // Populate defaults array.
71 'value' => $this->randomMachineName(32),
72 'format' => filter_default_format(),
74 'title' => $this->randomMachineName(8),
76 'uid' => \Drupal::currentUser()->id(),
78 $node = Node::create($settings);