8

This question describes how to set the value of a term reference field using PHP. But what do I do if I want to set the value of a term reference field in the user profile to multiple terms?

I am trying to set the value to term IDs 27 and 28. Here is my code so far:

$user->field_yourfield_name[LANGUAGE_NONE][0]['tid'] = 27;
user_save($user);
8

Assuming the field is set up to accept multiple records...

$user->field_yourfield_name[LANGUAGE_NONE][0]['tid'] = 27;
$user->field_yourfield_name[LANGUAGE_NONE][1]['tid'] = 28;
// etc

Or you can just keep appending to the array (without knowing the next available index) like this:

$user->field_yourfield_name[LANGUAGE_NONE][]['tid'] = 27;
$user->field_yourfield_name[LANGUAGE_NONE][]['tid'] = 28;
1

You can assign to a list value that contains entity metadata wrapper. For example:

<?php
  $wrapper = entity_metadata_wrapper('user', $user);
  foreach ($wrapper->field_taxonomy_terms->getIterator() as $delta => $term_wrapper) {
    // $term_wrapper may now be accessed as a taxonomy term wrapper.
    $label = $term_wrapper->name->value();
    $tid = $term_wrapper->tid->value();
    // you can also set the values
    $term_wrapper->name = 'New label';
    $term_wrapper->tid = array(123, 1234); // or ...
    $term_wrapper->tid->set($tids_to_set);
  }
  $wrapper->save();
?>

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.