1

I want to create a user programatically. But I have a field id proof where user can upload files.

But I don't know how to save that file while creating user.

Here is my code

$form_state = array();
$form_state['values']['name'] = 'robo-user';
$form_state['values']['mail'] = 'robouser@example.com';
$form_state['values']['pass']['pass1'] = 'password';
$form_state['values']['pass']['pass2'] = 'password';
$form_state['values']['op'] = t('Create new account'); 
//need to know about files 

drupal_execute('user_register', $form_state);

Can anybody tell me how to do this

Thanks

1

Hope this will help you.

In Drupal 7 you can use file_save_data and file_usage_add.

  • file_save_data : Saves a file to the specified destination and creates a database entry.
  • file_usage_add : Records that a module is using a file.

    global $user;
    $path = 'C:\...\Downloads\sample images\drupal_7_icon_0.jpg';//local path of id proof image
    $filename = drupal_basename($path);//get filename
    $file_temp = file_get_contents($path);
    //Saves a file to the specified destination and creates a database entry.
    //Dont forget to create id_proof folder inside files folder
    $file_temp = file_save_data($file_temp, 'public://id_proof/' . $filename, FILE_EXISTS_RENAME);

    // Record that the module (in this example, user module) is using the file. 
    file_usage_add($file_temp, 'mymodule_name', 'user', $user->uid);//change the module name

    //Get the values to create new user
    $form_state = array();
    $form_state['values']['name'] = 'robo-user';
    $form_state['values']['mail'] = 'robouser@example.com';
    $form_state['values']['pass']['pass1'] = '1234';
    $form_state['values']['pass']['pass2'] = '1234';
    $form_state['values']['op'] = t('Create new account');
    $form_state['values']['field_user_id_proof'][LANGUAGE_NONE][0]['fid'] = $file_temp->fid;//change it as per your requirement
    drupal_form_submit('user_register_form', $form_state);
    drupal_set_message('User saved successfully');

  • $file_temp = file_save_data($file_temp, 'public://id_proof/' . $filename, FILE_EXISTS_RENAME); this returns filesize=0 – Hitu Bansal Aug 31 '13 at 7:55
  • Can you check the filesize of the file which your are uploading. – inizio Sep 2 '13 at 14:45

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.