0

I seem to struggle with a problem which has already been answered. I have a 'review' form on which there is a field that I want to prepopulate. It is a term reference field and I want it to be prepopulated with taxonomy values from another node. I have looked at this issue without success. Any help would be greatly appreciated.

function my_module_form_alter(&$form, &$form_state, $form_id) {
      $nodeid=$_GET['id']; 
      $node=node_load($nodeid);
      if ($form_id == 'review_node_form') {     
        $form['field_revactivities']['und'][0]['value']['#default_value'] = $node->field_ad_tags['und'][0]['tid'];
      }
}

I know that '$node->field_ad_tags['und'][0]['tid']' returns the number of the term, but I am not sure how to get the value into the new field.

Also, if there are multiple terms for the field, should I populate the field for each term by incrementing [0], then ['1'], etc...?

0

Answering my own question: 1) First aspect is to feed the data correctly to the term reference field. The magic formula I found is:

$form['field_revactivities'][LANGUAGE_NONE]['#default_value'] = array($bidule);

where $bidule is a the string of taxonomy term (not its taxonomy id).

2) If there are multiple elements in the field_ad_tags, then I had to create a loop to place them all one after the other in a string. It was important to have the exact wording of each taxonomy term for the field to recognise which tag it is and to separate them with a comma. Here is my final code:

$bidule = '';
$i=0;
foreach ($node->field_ad_tags['und'] as $truc => $value) {
        drupal_set_message('<pre>$truc '. print_r($value, TRUE) .'</pre>');
        $term = taxonomy_term_load($node->field_ad_tags['und'][$i]['tid']);
        $name = $term->name;
        $bidule= $bidule.','.$name;
        $i++;
}
$bidule=substr($bidule, 1); // Remove the first character ','

$form['field_revactivities'][LANGUAGE_NONE]['#default_value'] = array($bidule);

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.