I have followed the official Form API Documentation, but this code don't work for me on Drupal 8:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['upload'] = array(
      '#title' => t('Upload Images'),
      '#type' => 'managed_file',
      '#upload_location' => 'public://image_example_images/',
      '#element_validate' => array('file_generic_settings_max_filesize'),
    return $form;

  private function file_generic_settings_max_filesize($element, &$form_state) {
    form_error($element, 'This is an error.');

I have trying to remplace form_error() by $form_state->setErrorByName() but same problem, the file is uploaded and the validation is not called.

Have you a solution please ? The documentation of #element_validate is outdated ?

My objective: Upload a lot of images, use a custom validation and insert all images thumbnails inside a <div class="preview"></div> with a field for name each images.

Example: enter image description here (After upload, display thumbnails and title field for name all each images)

Else, after upload, for display Thumbnails and other field (title and description) for each image, I need to use #value_callback, #process, #attached (manage field/display with js after upload) or an other option please ?


1 Answer 1


To use an instance method for #element_validate/#value_callback etc you need a callable. e.g.

$form['upload'] = array(
  '#title' => t('Upload Images'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://image_example_images/',
  '#element_validate' => array(
    array($this, 'file_generic_settings_max_filesize'),

You'll need to mark file_generic_settings_max_filesize() (which if you were being a stickler for standards should really be named fileGenericSettingsMaxFilesize) as public to accommodate, as your class won't be invoking the method.

Documentation for this is ongoing, the change notice is here.

  • 4
    If it is a method on the form object, then array('::file_generic_settings_max_filesize') can be used, see drupal.org/node/2325875
    – Berdir
    Dec 18, 2014 at 21:53
  • I just added more details to the example in the change notice, and added the documentation issue as related to it.
    – colan
    Sep 8, 2016 at 3:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.