views:

291

answers:

1

I'm trying to validate that an uploaded file really does have the .csv extension. This code isn't working, however:

function upload_validate($form, &$form_state) {
        // code that does work ...
 else {
  $file = file_save_upload('upload');
  $errors = file_validate_extensions($file, 'csv');
  if (! empty($errors)) {
   form_set_error('', $errors[0]);
  }
  else {
   $_SESSION[FILE_KEY] = serialize($file);
  }
 }
}

What am I doing wrong?

A: 

<wrong>
I think your problem is with form_set_error(). Here is the actual function (with an annotation):

<?php
function form_set_error($name = NULL, $message = '', $reset = FALSE) {
  static $form = array();
  if ($reset) {
    $form = array();
  }
  // here is where setting $name to '' is a problem
  if (isset($name) && !isset($form[$name])) { 
    $form[$name] = $message;
    if ($message) {
      drupal_set_message($message, 'error');
    }
  }
  return $form;
}
?>

I think the problem is you are passing an empty string to $name so form_set_error sees that name is set but there cannot be an array key that is an empty string. I would try calling the function like this:

form_set_error(, $errors[0]);

</wrong> (When I frist wrote this I didn't read the '!' inf front of the isset() of the line after the commetn I added to the code. I would try passing a string that is not in any part of the $form array to see what happens, but probably try the answer below)

Other than that, from looking at the API Documentation for file_validate_extensions() it looks like the code you have written should work. Have you tried using something like drupal_set_message() to check that part of your if blocks are begin run when you think that they should be. It might be that there is something wrong with your if logic.

bearver