1

I enabled latest version of media module to upload images in wysiwyg. It is working fine. There is no problem. I want to upload images programmatically from media library.
Below is my code.

function test_form_upload_form_alter(&$form, $form_state) {
 $form['settings']['apply_now_image'] = array(
  '#type' => 'media',
  '#title' => 'Image for apply now',
 );
 $form['#submit'][] = 'test_upload_form_submit';
}

function test_upload_form_submit(&$form, $form_state) {
    global $user;
    if (!empty($form_state['values']['apply_now_image'])) {
    $file = file_load($form_state['values']['apply_now_image']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    // Save.
    file_save($file);
    file_usage_add($file, 'user', 'user', $user->uid);
    $apply_now_image_path = file_create_url($file->uri);
    variable_set('rgit_apply_now_image', $apply_now_image_path);
    variable_set('rgit_apply_now_image1', $file->fid);
  }
}

But it didn't give correct answer. This is only work if the '#type' is managed_file'. It didn't work if the '#type' is media. Is any solutions there to upload images from media library.

1
  • You need to declare $user as global in the submit function? : file_usage_add($file, 'user', 'user', $user->uid); – PHP Team Mar 3 '15 at 10:27
0

Not sure what you are trying to achieve here, but files uploaded via media are already permanent managed files once you get to the submit stage, I believe.

The value in the form_state array you need is $fid = $form_state['values']['apply_now_image']['fid']);

You can then use that in a file_load: $file = file_load($fid);

So your code becomes

$file = file_load($form_state['values']['apply_now_image']['fid']);
file_usage_add($file, 'user', 'user', $user->uid);
$apply_now_image_path = file_create_url($file->uri);
variable_set('rgit_apply_now_image', $apply_now_image_path);
variable_set('rgit_apply_now_image1', $file->fid);
1
  • You have described here how to upload image in drupal. I can understood this. But i want to know how to upload image using by '#type' => 'media' – phponwebsites Apr 16 '15 at 13:30

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.