Mister G
Mister G

Reputation: 175

Drupal 7 set user picture (avatar) programmatically

I have form with file upload element. This file (image) must be user picture, but it not set.

form:

      $form['f']['step4']['file_e'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
    '#upload_location' => 'public://images/',
  );

validate

function fill_up_profile_form_validate($form, &$form_state) {
  global $user;

  if (isset($form['f']['actions']['submit']['#value']) && $form_state['triggering_element']['#value'] == $form['f']['actions']['submit']['#value']) {
    $file = file_load($form_state['values']['f']['step4']['file_e']);
    $validators = array(
      'file_validate_is_image' => array(), 
      'file_validate_size' => array(1 * 1024 * 1024),
    );

    $errors = file_validate($file, $validators);
    if (!empty($errors)) {
      $message = '';
      foreach ($errors as $error)
        $message .= $error . '<br/>';

      form_set_error('Error!', $message);
    } else {
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
      $edit['picture'] = $file;
      user_save($user, $edit);
    }
  }
}

Thank you for your help.

Upvotes: 1

Views: 1058

Answers (1)

Bhavin Joshi
Bhavin Joshi

Reputation: 522

You should try with $form_state instead of $form. $form_state contains the submitted values! Also, with Drupal 7.x, you can not get the values by simply using $form_state['values']['f']['step4']['file_e']! Just do a echo "<pre>"; print_R($form_state); echo "</pre>"; to learn the correct structure of the array!

Also have a look at this code: http://ly2.in/hBMxPK

Upvotes: 1

Related Questions