Skip to content

Instantly share code, notes, and snippets.

@opi
Created December 3, 2012 08:34
Show Gist options
  • Save opi/4193667 to your computer and use it in GitHub Desktop.
Save opi/4193667 to your computer and use it in GitHub Desktop.
Drupal: Admin form for file
<?php
function mymodule_admin_image() {
$form = array();
// Image wrapper
$form['image_default'] = array(
'#type'=>'fieldset',
'#title' => "Image par defaut",
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
// Image preview
$form['image_default']['mymodule_image_default_preview'] = array(
'#markup' => theme(
'image_style',
array(
'style_name' => 'medium',
'path' => variable_get('mymodule_image_default', "")
)
),
);
// Image path
$form['image_default']['mymodule_image_default'] = array(
'#type' => 'textfield',
'#disabled' => TRUE,
'#size' => 25,
'#default_value' => variable_get('mymodule_image_default', ""),
);
// Image upload file
$form['image_default']['mymodule_image_default_upload'] = array(
'#type' => 'file',
'#maxlength' => 40,
);
$form = system_settings_form($form);
// We don't want to call system_settings_form_submit(), so change #submit.
array_pop($form['#submit']);
$form['#submit'][] = 'mymodule_admin_image_submit';
$form['#validate'][] = 'mymodule_admin_image_validate';
return $form;
}
function mymodule_admin_image_validate($form, &$form_state) {
// Handle file uploads.
$validators = array(
'file_validate_is_image' => array(),
'file_validate_extensions' => array('jpg jpeg'),
);
$file = file_save_upload('mymodule_image_default_upload', $validators);
if (isset($file)) {
if ($file) {
$form_state['values']['mymodule_image_default_upload'] = $file;
}
else {
form_set_error('mymodule_image_default_upload', "Error");
}
}
} // mymodule_admin_image_validate
/**
* Process system_theme_settings form submissions.
*/
function mymodule_admin_image_submit($form, &$form_state) {
$values = $form_state['values'];
if ($file = $values['mymodule_image_default_upload']) {
unset($values['mymodule_image_default_upload']);
variable_set('mymodule_image_default', file_unmanaged_copy($file->uri));
}
drupal_set_message(t('The configuration options have been saved.'));
//cache_clear_all();
} // mymodule_admin_image_submit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment