[Drupal] How to get profile picture uploading option programmatically during registration

| | 2 min read

In Drupal we have got a module namely Registration with Profile , to bring an option to upload the profile picture. But here let us gather some information on how this can be brought programmatically.
So let's start up with Form API.
Following are the steps to get the profile picture uploading option in registration form.

Step 1 : In registration form alter :

 
  $form['profile_pic'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('The image style chosen below would be applied for this uploaded image.'),
    '#default_value' => variable_get('profile_pic', ''),
    '#upload_location' => 'public://profile_pic_images/',
  );

Here our profile picture is now stored inside the folder 'profile_pic_images'.

Step 2 : Next save the picture using hook_user_presave.


function mymodule_user_presave(&$edit, $account, $category) {
  // Only for new users who have an uploaded image.
  // user_save() will handle old users.
  $edit['picture'] = $edit['picture_new'];
}

Step 3 : Implements the hook theme to theme the uploaded image.


function mymodule_theme() {
  return array(
    'image_multifield_multitype' => array(
      'render element' => 'element',
    ),
  );


}

Step 4 : Function to return the uploaded image in thumbnail format.


/**
 * Returns HTML content for a managed file element with thumbnail.
 */
function theme_image_multifield_multitype($variables) {
  $element = $variables['element'];
  $output = '';
  if($element['fid']['#value'] != 0) {
    // Show its thumbnail to the output HTML, only if image is uploaded 
     $output.="<div class='multifield-thumbnail'>";
    $output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => file_load($element['fid']['#value'])->uri, 'getsize' => FALSE));
    $output .= drupal_render_children($element); // renders rest of the element as usual
    $output .= '</div>';
  }
  return $output; // of course, has to be returned back
}

By using the 'managed_file' as the type, the Form API provides us a widget to upload images.Thus uploading is not complete until we view our profile picture in our profile page. For that we need to save the uploaded image, for that purpose we save the picture using the hook, hook_user_presave.

Now we have implemented an option to upload profile picture in our registration form, this would be complete if we are able to preview our uploaded image.To preview our uploaded image is hence described in step 3 and 4.In Step we write hook_theme to theme our uploaded image.And finally in Step 4 we return the uploaded image in thumbnail format.

That is it and you are done !!