Created
June 2, 2016 16:17
-
-
Save flocondetoile/a122225111f2169d471294a22a2107ce to your computer and use it in GitHub Desktop.
create node programmatically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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