Search code examples
drupaldrupal-7

Drupal 7, hook_file_presave display error message and stop uploading file


I am new to drupal 7, I am trying to create hook_file_presave / hook_file_validate / hook_field_validate function, That checks if pdf file that is uploaded on site is not password protected.

I can easily check using php if file is password protected. But when I display error message, it only displays error message also uploads file. I think i am not using right hook.

function simpletest_file_presave($destination){
    // here is my logic

    drupal_set_message(t('file is encrypted >>>>>>>> '. $filename), 'error');
    return;
}

Here you can see file shouldn't be uploaded buit its there with remove button.


Solution

  • It's been a while since I've touched Drupal, but I first thought about hook_file_validate().

    But as explained here you could implement hook_form_FORM_ID_alter() in order to add your own file upload validator and then return an array of errors to display.

    Important: When you use the t() function to translate your message don't append the filename to your string because this will create multiple translated strings, one for each uploaded file so it will never be translated as it will always vary. To avoid that, use a placeholder and pass the filename as string parameter, like this:

    $error_message = t(
      'The file "@filename" is encrypted! Please upload a PDF without password protection.',
      ['@filename' => $filename_without_path]
    );
    

    See the API documentation for the t() and format_string() functions