1

I'm using an approach similar to the one taken in this question. The difference is that I have a taxonomy term reference field in the user profile that I want to use to prepopulate a custom content type.

To prepopulate a text field on a custom content type with a value from the user profile, I have added this code to a custom module:

function MYMODULE_form_MYFORM_node_form_alter(&$form, &$form_state, $form_id) {
 // test if node for has been assigned a NID. If not then populate fields with default data */
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))){
    global $user;
    $user_fields = user_load($user->uid);
    //set age
    if (isset($user_fields->field_acc_age['und'][0]['value'])){

      $form['field_ad_age']['und'][0]['value']['#default_value'] =  $user_fields->field_acc_age['und'][0]['value'];
    }

However, when attempting to prepopulate a taxonomy term reference field from the user profile to the custom content type, the above code doesn't work; there is no error, but the value is not carried across. I assume this is because term references are stored differently in the DB, but I don't understand how to change the code to make it work.

1 Answer 1

4

Try the following code.

function MYMODULE_form_MYFORM_node_form_alter(&$form, &$form_state, $form_id) {
  // Check if the node has a node ID. If not, then populate the fields with the default data.
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))) {
    global $user;
    $user_fields = user_load($user->uid);
    // Set age.
    if (isset($user_fields->field_acc_age['und'][0]['tid'])) {
      $form['field_ad_age']['und'][0]['value']['#default_value'] = $user_fields->field_acc_age['und'][0]['tid'];
    }
  }
}
1
  • $user_fields->field_acc_age['und'][0]['tid']; would set form field value to numeric tid instead of term name. How to make it set to term name just like it worked when we set manually filling form?
    – kiranking
    Commented Mar 20, 2015 at 18:28

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.