Score:0

How to Update Multi Value Entity Reference Field Programatically

fr flag

I have two Node Content Types type_a and type_b I have a field called as field_author_profile in type_a which is entity reference field to type_b with cardinality unlimited.

How do I update field_author_profile programatically.

I also need to Check if value already exists in the field , if exists then append the new value while updating the field value or else just assign the value.

I tried the below variants but seems none worked .

$author_object->set('field_author_profile', $author_profile_nid);

$author_object->field_author_profile = ['target_id' => $author_profile_nid];

$author_object->field_author_profile->entity->target_id->value = $author_profile_nid;

$author_object->field_author_profile[] = ['target_id' => $author_profile_nid];

$author_object->field_author_profile->target_id = $author_profile_nid;

$author_object->get('field_author_profile')->setValue(['target_id' => $author_profile_nid]);

Saved the node after this by using

$author_object->save();

Edit : The field value was not being rendered in the node edit form, even thought it was present in the database. It was due to the wrong bundle type selected in the entity reference field. Once it is corrected it worked as expected.

This was the working solution.

$author_object->field_author_profile[] = ['target_id' => $author_profile_nid];
miststudent2011 avatar
fr flag
Related https://drupal.stackexchange.com/questions/213379/programmatically-update-an-entity-reference-field
cn flag
Your 4th example is the correct one. It’s also the only one not using `field_author_profile`, which could be the problem
miststudent2011 avatar
fr flag
@Clive, Thanks for the response . It was a typo corrected it.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.