1

I am having trouble figuring out how to attach an uploaded image to a node in my form submit handler. I've been searching for a while now and nothing I've tried has worked. For instance:

$image = $form_state['storage']['image'];
unset($form_state['storage']['image']);
$image->status = FILE_STATUS_PERMANENT;
$file = file_save($image);
$node->field_image['und'][0] = $file;

does not work.

Any help on this would be much appreciated. Thanks.

7
  • If I recall correctly you need $node->field_image['und'][0] = (array) $file; and then you need to call node_save($node); after that.
    – Jaypan
    Commented Feb 16, 2017 at 16:14
  • @Jaypan I have tried that as well. I've been at this for over an hour, and have tried basically everything on Google.
    – aperture
    Commented Feb 16, 2017 at 16:23
  • How is it not working?
    – Jaypan
    Commented Feb 16, 2017 at 16:24
  • @Jaypan Well, first off, I get "undefined index storage" so I've replaced that with ["values"]["image"]. But the uploaded image does not get attached to the node. I've tried a var_dump($form_state['values']['image']) (as well as ['storage']), but that gives me an empty string. And no matter what I do, I don't get an image attached to the node.
    – aperture
    Commented Feb 16, 2017 at 16:27
  • 1
    What is the form element defined as? If it's type 'file', then the uploaded data will be part of the $_FILES global. Usually it's better to create the element as type 'managed_file' though, in which case the value in the submit will be the file ID of the uploaded file, and you don't need to touch the $_FILES global.
    – Jaypan
    Commented Feb 16, 2017 at 16:31

1 Answer 1

0

It's been a while since I've done this but this link should be a good start. File Load

Assuming $form_state['storage']['image'] is the image's fid, what you may want to do is.

$image = $form_state['storage']['image'];
$file = file_load($image);

// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;

// Save.
file_save($file);

// add image back
$node->field_image['und'][0] = $image;

Depending on what your doing you may want to add the file to the usage table. Details here. File Usage Add

2
  • 1
    Thank you. This finally worked after switching to 'managed_file' as the type.
    – aperture
    Commented Feb 16, 2017 at 17:02
  • No problem, I forgot about that being necessary. Glad you worked it out.
    – J.Floyd
    Commented Feb 16, 2017 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.