2010-01-03 16 views
5

Per qualche motivo, il mio modulo si interrompe quando provo a rendere necessario il caricamento di un file. Ecco il codice per esso:Drupal: è richiesto il caricamento di file?

$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'); 

su un supporto Drupal site, qualcuno dice che è impossibile fare upload di file necessari. È vero?

+0

Come ci si rompe? stai ricevendo un messaggio di errore? – Evert

+0

Non consente all'utente di inviare il modulo, anche se è stato selezionato un file per il caricamento. –

risposta

3

Questa è la mia soluzione per rendere campo del file richiesto:

<?  
    // 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

funziona per richiedere il caricamento, ma non convalida correttamente l'estensione del file. Sono stato in grado di caricare un jpg. –

+0

Scusa, hai ragione. L'ho risolto. Ancora la convalida del tipo di file non funziona per il primo utente. – Kniganapolke

0

Non sono un esperto di Drupal ma è possibile controllare se la variabile $_FILES esiste, no?

Problemi correlati