0

I'm trying to load a node by a value in a custom field (field_one) to change the value of another custom field (field_two) on that node.

I am using the following code to load the node:

$nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_one' => $fieldValue]);

I am then trying to update the value of "field_two" using the following code:

if ($node = reset($nodes)) {

    $node->set('field_two', 'New value');
    $node->save();
}

The above results in the error "InvalidArgumentException: Field field_two is unknown... "

It works if I try to set the value of the title ( $node->set('title', 'New value') ) but I can't get it to work for custom fields?

3
  • 1
    You could have a content type that has field_one but not field_two.
    – No Sssweat
    Apr 27 '20 at 20:44
  • Ok, so I need to add a content type (bundle) in my IF statement? Apr 27 '20 at 20:46
  • 2
    WOW.. I spent 8 hours trying to figure this out and all was missing was to specify the content type! I was about to go insane.. Thanks a bunch! :D Apr 27 '20 at 20:53
2

Thanks to the comment by @No Sssweat I realized that I simply needed to specify a content type:

$nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_one' => $fieldValue, 'type' => 'CONTENT_TYPE']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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