Drupal: File upload required?

与世无争的帅哥 提交于 2019-12-05 11:39:46

This is my workaround to make file field required:

<?    
    // A piece of form that defines the file field
    $form['attachment'] = array(
        '#type' => 'file',
        '#title' => t('Title'),
        //'#required' => TRUE,  // check this manually
    );

    // Form validation hook
    function yourformname_validate($form, &$form_state) {
        // Validate file
        $validators = array(
            'file_validate_extensions' => array('doc txt pdf'), // does not work for user 1
            'file_validate_size' => array(1000000, 0),
        );
        $file = file_save_upload('attachment', $validators, file_directory_path());
        if ($file) {
             $form_state['values']['attachment'] = $file; // drupal file object
        }
        else{
             form_set_error('attachment', "File is required");
        }
    }
?>

I'm not a Drupal expert but you could check if the $_FILES variable exists, no?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!