Drupal 7 adding user profile picture at registration

It took me a while to get this working and since I’m sure others will be struggling with the same task I decided to share my code.

Here’s my approach, all stored in a module called “customers”

  1. Alter “user-register-form” found at www.your-domain.com/user/register
  2. Add custom submit handler to “user-register-form” form
  3. Upload user image in custom submit handler

it really is that simple :)

Using hook_form_FORM_ID_alter() to alter “user-register-form” making sure I only hook into that form.

Inside this function which in my case is called “customers_form_user_register_form_alter” I add a few attributes to the form so that it can handle file uploads:

$form['#attributes'] = array(
  'enctype' => 'multipart/form-data',
  'autocomplete' => 'off'
);

then add custom submit handler like so:

$form['#submit'][] = 'customers_register_handler';

and then the field that holds the image file:

$form['picture_upload'] = array(
  '#type' => 'file',
  '#title' => t('Company Logo')
);

in my case I use the user profile picture to store a company logo, but it’s just the title of the field. And now to where the magic happens; the custom submit handler:

$validators = array(
  'file_validate_is_image' => array(),
);
$file = file_save_upload('picture_upload', $validators);

if ($file == false) {
  form_set_error('picture_upload', t('Failed to upload picture'));
  $picture = null;
} elseif ($file != null) {
  $picture = $file;
  // Set the user id
  $picture->uid = $user->uid;
}

user_save($user, array(
  'picture_upload' => $picture,
));

One of the things that took me a bit of time to grasp was the fact that files are not passed inside the $form_state array, instead you call file_save_upload() where the 1. parameter is the name of the file field. In my case the file field is called picture_upload, and as you can see I’m currently not passing any file validation. The next “if statement” just takes care that a file was uploaded and sets the owner to the newly created user.

The only thing left is to call user_save() and pass in the file that was uploaded.

I know several modules exist that handle this for you, but adding a module just for that is an overkill in my opinion, especially since all my other logic related to “customers” is stored inside my customers.module.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.