2010-01-03 40 views
5

由于某些原因,当我尝试进行文件上传时,表单会中断。下面是它的代码:Drupal:需要上传文件吗?

$form_id = "upload_form"; 

$form[$form_id] = array (
    '#type' => 'fieldset', 
    '#description' => t('This is a utility to import nodes from a Comma Separated Value file. To begin, pick a node type, and upload a CSV.'), 
); 

$form[$form_id]['type'] = array(
    '#title' => t('Enter node type'), 
    '#type' => 'textfield', 
//  '#autocomplete_path' => '', TODO: autocomplete for node types 
    '#required' => TRUE, 
    '#description' => t('This node type should already exist. If it doesn\'t, create it first.'), 
); 

$form[$form_id]['upload'] = array(
    '#type' => 'file', 
    '#title' => t('Upload CSV file'), 
//  '#size' => 40, 
    '#description' => t('This will not work for a non-CSV file.'), 
//  '#required' => TRUE, TODO: breaks it. why? 
); 

$form[$form_id]['submit'] = array(
    '#type' => 'submit', 
    '#value' => t('Submit'), 
); 

$form['#attributes'] = array('enctype' => 'multipart/form-data'); 

在一个Drupal支持site,有人说,这是不可能使所需的文件上传。这是真的?

+0

它是如何突破?你是否收到错误信息? – Evert 2010-01-04 09:18:34

+0

即使选择了上传文件,也不会让用户提交表单。 – 2010-01-04 18:28:03

回答

3

这是我的解决方法,以使文件必填字段:

<?  
    // 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"); 
     } 
    } 
?> 
+0

这适用于要求上传,但它不适当地验证文件扩展名。我能够上传一个JPG。 – 2010-01-07 23:34:12

+0

对不起,你是对的。我修正了这个问题。仍然验证文件类型不适用于第一个用户。 – Kniganapolke 2010-01-08 08:24:10

0

我不是Drupal专家,但你可以检查是否存在$_FILES变量,不是吗?