Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save flocondetoile/a122225111f2169d471294a22a2107ce to your computer and use it in GitHub Desktop.
Save flocondetoile/a122225111f2169d471294a22a2107ce to your computer and use it in GitHub Desktop.
create node programmatically
/**
* @param string $type
* @param string $title
* @param string $langcode
* @param string $uid
* @param array $fields
* @param bool $promote
* @param bool $status
* @return \Drupal\node\Entity\Node $node
*/
public function createNode ($type, $title, $langcode, $pattern ='' , $uid = '1', $fields = [], $promote = FALSE, $status = TRUE){
// Add trailing slash to the pattern and build the path
$pattern = empty($pattern) ? '' : $pattern . '/';
$path = '/' . $pattern . $this->cleanAlias($title, $langcode);
/** @var \Drupal\node\Entity\Node $node */
$node = Node::create(array(
'type' => $type,
'title' => $title,
'uid' => $uid,
'status' => $status,
'promote' => $promote,
'langcode' => $langcode,
'path' => $path,
));
if (empty($fields)) {
$node->save();
return $node;
}
else {
foreach ($fields as $field_name => $value) {
if ($node->hasField($field_name)) {
$node->set($field_name, $value);
}
}
$node->save();
return $node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment