
Upload files via Form API

Because I didn’t get this process right away, I decided to describe it, maybe someone will come in handy and help.
To make it more interesting, I will describe on creating a module for randomly displaying pictures.
Task
The task is precisely the implementation of the ability to upload files to Drupal through the Form API. And the example described below is just an example of this implementation.Functional
We will have an admin area where you can add or remove images. There will also be a function that will return a randomly selected picture from the admin panel. Everything is very simple:)Implementation
First you need to create a page in the admin panel with our settings.Copy Source | Copy HTML- /**
* Implementation of hook_menu().
*/ - function ivt_header_menu() {
- $items['admin/settings/ivt_header_settings'] = array(
- 'title' => t('IVT Header Settings'),
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('_ivt_header_settings_form'),
- 'access arguments' => array('access administration pages'),
- 'type' => MENU_NORMAL_ITEM,
- );
-
- return $items;
- }
We describe the form itself with a list of downloaded files for deletion, a field for downloading a file, and a button.
Copy Source | Copy HTML- function _ivt_header_settings_form(){
- $form['#attributes']['enctype'] = 'multipart/form-data';
-
- $form['header_images_del'] = array(
- '#type' => 'checkboxes',
- '#title' => t('Delete images'),
- '#options' => variable_get('ivt_header_images', array()),
- );
-
- $form['header_images_upload'] = array(
- '#type' => 'file',
- '#title' => t('Attach new image'),
- );
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Go!')
- );
-
- return $form;
- }
It will look like this:

We will write a validator for this form, in which we will upload the image to the site.
Copy Source | Copy HTML- function _ivt_header_settings_form_validate($form, &$form_state){
- if (isset($form['header_images_upload'])) {
- //валидация на расширение файла
- $validators = array('file_validate_extensions' => array('png'));
-
- //папка, куда будет загружаться файл
- $dir = file_directory_path() . '/headers';
-
- //проверяем существует ли директория. если ее нету, то она создастся
- if(file_check_directory($dir, 1)) {
- //загружаем файл
- $file = file_save_upload('header_images_upload', $validators, $dir);
-
- //добавляем в $form_state новое поле с файлом
- if ($file) $form_state['values']['header_image_file'] = $file;
- }
- }
- }
In the submission we will delete the selected files and add new ones.
Copy Source | Copy HTML- function _ivt_header_settings_form_submit($form, &$form_state){
- $image_file = $form_state['values']['header_image_file'];
- $images_del = $form_state['values']['header_images_del'];
- $images_del = array_filter($images_del);
-
- //получаем список уже загруженых файлов
- $header_images = variable_get('ivt_header_images', array());
-
- //если при сабмите был выбран файл для загрузки
- if ($image_file) {
- //добавляем его в наш список
- $header_images[$image_file->fid] = l($image_file->filename, $image_file->filepath);
- drupal_set_message(t('Image %filename has been uploaded!', array('%filename' => $image_file->filename)));
- }
-
- //если при сабмите были отмечены файлы для удаления
- if ($images_del){
- //пробегаемся по всем файлам
- foreach ($images_del as $fid){
- //загружаем файл из базы данных
- $sql_file = db_fetch_object(db_query("SELECT filepath, filename FROM files WHERE fid = '%s'", $fid));
-
- //удаляем файл из базы данных
- db_query('DELETE FROM {files} WHERE fid = %d', $fid);
- //удаляем файл
- file_delete($sql_file->filepath);
-
- //удаляем файл из нашего списка
- unset($header_images[$fid]);
- drupal_set_message(t('Image %filename has been removed!', array('%filename' => $sql_file->filename)));
- }
- }
- //сохраняем наш список
- variable_set('ivt_header_images', $header_images);
- }
It remains only to write a function that would take an arbitrary picture from our list and return it.
Copy Source | Copy HTML- function ivt_header_get_image($fid = null){
- global $base_url;
- //если аргумента нету, то берем произвольно
- if (!$fid){
- //загружаем список
- $header_images = variable_get('ivt_header_images', array());
- //берем случайную
- $fid = array_rand($header_images);
- }
-
- //получаем путь до картинки
- $sql_file = db_fetch_object(db_query("SELECT filepath FROM files WHERE fid = '%s'", $fid));
- $filepath = $sql_file->filepath;
-
- $image_html = "
"; -
- //возвращаем картинку
- return $header_images ? $image_html : '';
- }
That's all.