2010-01-03 13 views
5

Por alguna razón, mi formulario se rompe cuando intento hacer una carga de archivo requerida. Aquí está el código para ello:Drupal: ¿Se requiere subir un archivo?

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

Sobre un soporte de Drupal site, alguien dice que es imposible hacer la carga de archivos requeridos. ¿Es esto cierto?

+0

¿Cómo se rompa? ¿Está recibiendo un mensaje de error? – Evert

+0

No permite que el usuario envíe el formulario, incluso cuando se ha seleccionado un archivo para cargarlo. –

Respuesta

3

Ésta es mi solución para hacer campo de archivo requerido:

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

esto funciona para requerir la carga, pero no valida correctamente la extensión del archivo. Pude subir un jpg. –

+0

Lo siento, tienes razón. Lo he arreglado Todavía la validación del tipo de archivo no funciona para el primer usuario. – Kniganapolke

0

No soy un experto de Drupal pero puede verificar si existe la variable $_FILES, ¿no?

Cuestiones relacionadas