2

I'm trying to import some nodes into a new D8 installation. Therefore I wrote a module. Importing nodes is already working perfectly. As you can see in my code snippet, I'm using the $field_array variable to create the nodes. Now my questione: is it possible to use this variable also for the node update functionality?

Regards

M.

 public function ausgabe($import_node,$action,$new_old_uid,$new_old_nid) {
    global $content_type;


    $lang = $this->get_current_language();

    $field_array = [
        'uid' => $new_old_uid["new_uid"],
        'type' => $content_type,
        'langcode' => $lang,
        'status' => $import_node->status,
        'created' => $import_node->created ,
        'changed' => $import_node->changed ,
        'title' => $import_node->title,
        'body' => [
            'summary' => "",
            'value' => (isset($import_node->body) && !empty($import_node->body)) ? $import_node->body : "",
            'format' => 'full_html',
        ],
        'field_teaser' => [
            'value' => (isset($import_node->teaser) && !empty($import_node->teaser)) ? $import_node->teaser : "",
            'format' => 'full_html',
        ],
        'field_onid' => array('value'=>$import_node->nid),
        'field_image' =>  $this->get_set_images($import_node->field_ausgabe_bild),
        'field_files' => $this->get_set_files($import_node->files),
    ];

    if($action == "create") {
        $node = Node::create($field_array);
    } else {
        $node = Node::load($new_old_nid["new_nid"]);

    }
    $node->save();

    \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), '/'.$import_node->path, $lang);
    echo $action.": Node " . $import_node->title . ' ('.$node->id().') <br>';

    $this->pre("",true);

}
2
  • Looping over it works, but why bother building an array in the first place, why don't you just assign those keys directly to the node object as you build them?
    – Berdir
    Sep 13, 2016 at 21:23
  • because i searched a way to create a node and found one, that used this way ( drupal.stackexchange.com/questions/185442/… ). But when I recognized that the other way for updating nodes would be better, it was already too late and I was too lazy to make everything new ;). On the other hand it was quite a good exercise, how you can solve this with other approaches ;)
    – themca
    Sep 14, 2016 at 5:14

1 Answer 1

4

There seems to be no method to update a complete node.

But you can do this on a field basis:

foreach ($field_array as $field => $values) {
  $node->set($field, $values);
}
1
  • i just found out another solution: foreach ($field_array as $key => $field) { $node->{$key} = $field; }
    – themca
    Sep 13, 2016 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.