0

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?

2 Answers 2

1

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.

1

appendItem takes an array.

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

2
  • I've edited the code accordingly: it adds the term to the vocabulary, but it doesn't link it to the field.
    – DamianFox
    Commented Aug 3, 2020 at 18:58
  • 2
    Is $profileEntity->save() called?
    – mradcliffe
    Commented Aug 3, 2020 at 19:23

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.