Drupal form api by standard doesn't allow for developer to use
'#required' => true
to make the form element to be "required".
We can circumvent the problem by utilizing the hook_validate and set the form element to error state if there is no file uploaded.
example :
Our upload form example
function test_form($form_state) { $form['upload'] = array( '#type' => 'file', '#attributes' => array('enctype' => "multipart/form-data"), // important because we are going to upload file ); // our submit button $form['submit'] = array( '#type' => 'submit', '#name' => 'upload', '#value' => t('upload file'), ); return $form; }
Our form validate example
function test_form_validate($form, &$form_state) { // build some validator $validators = array( // validate if the file is an image 'file_validate_is_image' => array(), // validate the maximum image size width x height in pixel 'file_validate_image_resolution' => array('125x125'), ); // test if file upload successful and validated using our validator strings if ($file = file_save_upload('file', $validators, $dest = FALSE, FILE_EXISTS_RENAME)) { // set the file status to permanent, if you don't set it to permanent either here or somewhere else in your code then when the cron runs drupal will delete the file database entry file_set_status($file, 'FILE_STATUS_PERMANENT'); // at this point $file contains object data for the particular uploaded file such as file fid ($file->fid), filepath ($file->filepath) etc. do print_r($file,TRUE) to find out more about the $file object data } // this is the actual validation that emulates the "required" state if (empty($file)) { // set the form element "file" to error state if the $file is empty due to no file uploaded and render "Image file required" message to drupal message form_set_error('file', 'Image file required'); } }
There you have it, emulating "required" state for form upload element in drupal 6