0

I have several different fields attached to my user (user type) which are used to temporarily save settings for that user (most are node references, set by rules/flags/buttons) Is there a way to auto populate a new node's fields based on tokens or rules so that every time a user starts to create a node, some of the fields are pre-populated based on the vales stored in the user's user fields? Note: I would like to expose these values to the user during the node creation process.

4

You should check out hook_form_alter. It would let you preload form values but still keep them editable.

Something like this would work to load something from the user's profile fields into the node form for new nodes.

<?php
  function custom_module_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
      case 'NODETYPE_node_form':
        global $user;
        $current_user = user_load($user->uid);
        // Set only on nodes that haven't already been saved
        if (!isset($form['#node']->nid)) {
          $form['field_YOUR_FIELD_NAME'][LANGUAGE_NONE][0]['value']['#default_value'] = 
            $current_user->field_YOUR_USER_FIELD[LANGUAGE_NONE][0]['safe_value'];
        }
      break;
    }
  }
?>
  • if both field are same(using add exiting) and multivalue will this simple(awesome) code works or should we have to loop through each field value. – kiranking Mar 17 '15 at 17:52
  • Hello @kiranking. This was for the original question where he was seeking to prepopulate a form with user data on a single field. If you had a user with a multivalue field and you wanted to pass that information into another multivalue field, then, yes, you would need to loop through them since the Form API is structured differently than the loaded user object. If all of the fields match, then you could probably pull the field names in from the user account and use a variable placeholder for that name in place of 'field_YOUR_FIELD_NAME' above. – merauluka Mar 17 '15 at 19:08
  • hmm, I was just thinking , having same machine name and same instance(for example machine name:field_name, cardinality 3) would make them easily loaded on each other. Thanks for the info. – kiranking Mar 19 '15 at 9:27

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.