Question

I'm trying to import user profiles data from a JSON file. Several fields are entity reference to vocabularies.
I'm able to create a new taxonomy term entity in the universities vocabulary bundle using the following code:

$term = Term::create([
  'name' => "University of Bologna", 
  'vid' => 'universities',
])->save();

Now I have to link this newly created term to a field contained in Profile Type. I'm testing the following code.

    $values = array(
        'type' => 'profile_type',
        'uid' => 3043,
    );
    $profileStorage = \Drupal::entityTypeManager()->getStorage('profile');
    $profileEntity = $profileStorage->create($values);
    $profileEntity->field_entry_university->appendItem($term);
    $profileEntity->save();

However, this approach doesn't work. How can I fix it?

Was it helpful?

Solution

EntityInterface::save() returns the status of the save operation, not the entity:

$term = Term::create([
  'name' => "University of Bologna", 
  'vid' => 'universities',
])->save();

$term is always 1.

So first assign the newly created entity to $term and then save it:

$term = Term::create([
  'name' => "University of Bologna", 
  'vid' => 'universities',
]);
$term->save();

Adding the entity should be no problem then:

$profileEntity->field_entry_university->appendItem($term);

It doesn't matter whether you add the target entity or the target ID.

OTHER TIPS

appendItem takes an array.

Try $profileEntity->field_entry_university->appendItem(['target_id' => $term->id());

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top