2

I am building a theme with ability to upload custom background images but now I am stuck at a point.

How do I properly add FILE field in drupal form via theme-setting.php and after that how can I get public url to this file in my template files??

Mohd Sakib
  • 471
  • 5
  • 11

1 Answers1

12

In your theme_form_system_theme_settings_alter hook you need to add the following form element:

  $form['theme_settings']['background_file'] = array(
    '#type'     => 'managed_file',
    '#title'    => t('Background'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('background_file'), 
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
  );

This will save the file id to your theme settigns variable 'background_file', notice that i set the upload location to theme/backgrounds, this will be inside your files folder.

Finally you'll get the complete URL to the file with file_create_url:

$fid = theme_get_setting('background_file');
$image_url = file_create_url(file_load($fid)->uri);

Edit:

In your template.php you can add in the theme_preprocess_page hook the variable so all the tpl's can access it, this is how:

function theme_preprocess_page(&$variables, $hook) {
    $fid = theme_get_setting('background_file');
    $variables['background_url'] = file_create_url(file_load($fid)->uri);
}

Hope this helps! :D

imekinox
  • 819
  • 1
  • 7
  • 10
  • What should I do if I decided to upload multiple files i.e `$form['theme_settings']['background_file'][] = array(...` – SaidbakR Jul 20 '14 at 17:08
  • 2
    This approach has a little limitation, it works temporary. i.e after sometime, the uploaded images is going to be deleted. The question is: how to make it permanent? – SaidbakR Jul 22 '14 at 19:07
  • @sємsєм is right. This is not a complete solution as the uploaded images are gone 6 hours later. Check my answer here for more info: http://drupal.stackexchange.com/a/136911/4861 or consult directly with the Drupal docs: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#managed_file - Good luck. – Mario Awad Nov 14 '14 at 14:35