You are here

Using the managed_file Form element type in your theme with Drupal 7

So I've been struggling with this for a while now, and since it was damn near impossible to find on the Drupal Answers Stack Exchange, Drupal forums, or on the internet in general, I'm posting it here so that someone else doesn't rip their hair out.

Therefore, I was very excited to find out that adding form elements to a theme's Settings page was so easy with Drupal; for some reason other CMS's I've worked with make this sort of a pain in the neck. With Drupal, all you have to do is create a theme-settings.php file in your theme's folder, and add a function that gets called to add the various form fields you would like. Fortunately, someone's already written a bit about it here:

Metal Toad blog - How to add theme settings in Drupal 7

I added a bunch of settings, and figured "Done!"

Unfortunately, my file uploads (Using the managed_file form field type) kept on disappearing! How odd!

Learning Drupal is really cool, but sometimes I stumble across something that I just don't see right away. In any case, that same page (managed_file documentation) tells us that the managed_file functionality only adds the file to the database TEMPORARILY, and if it's not marked with a "FILE_STATUS_PERMANENT" marker, then the next time cron gets run the file get's washed out automatically! They give you the code to make the STATUS change on the docs page, but I'm pretty dense, so it took me WAY longer than it should have to figure out that what I should do is add an if statement at the top of my THEMENAME_form_system_theme_settings_alter function that goes somewhat like this:


if($file = file_load(theme_get_setting('my_file_option'))){
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
drupal_set_message("File Saved.");
}

Granted, it does save the file automatically when the file gets uploaded via the ajax form field. However, when the user presses the "Save Configuration" button, the image is saved successfully and a message is posted to the top letting the user know.

Everyone else probably figured this out without any hassle; I'm just putting it for those of us that are not rocket scientists, I suppose.

Drupal theme by pixeljets.com D7 ver.1.1