#upload_validators missing error message [Update]

Upon further investigation it seems that the message isn't appearing due to the following javascript error:

"Uncaught TypeError: Cannot read property 'length' of undefined"





I'm not sure how to resolve this error, but the following issues may be related:


[D7] Duplicate HTML IDs are created for file_managed_file fields
Duplicate HTML IDs are created for file_managed_file fields


Description

I'm trying to create a custom form with some number of file upload fields (for now I'm using the hard-coded value 3).

I have added an #upload_validators attribute to the managed_file element that calls file_validate_extensions and passes in "doc" as the only valid filetype.

When I try to upload a .jpg, an error appears -- which is what I want. However, the error doesn't contain any text.

Any idea what I'm doing wrong?

Code

function mymodule_example1_form($form_state) {
  $num_docs = 3;

  // Build the number of name fieldsets indicated by $form_state['num_docs'].
  for ($i = 1; $i &lt;= $num_docs; $i++) {
    $form['managed_file'][$i] = array(
      '#type' =&gt; 'managed_file',
      '#title' =&gt; 'Managed File' . $i,
      '#progress_indicator' =&gt; 'throbber',
      '#progress_message' =&gt; 'Upload successful!',
      "#upload_validators"  =&gt; array("file_validate_extensions" =&gt; array("doc")),
      '#upload_location' =&gt; 'public://doc/',
    );
  }

  $form['submit'] = array(
    '#type' =&gt; 'submit',
    '#value' =&gt; t('Submit'),
  );

  return $form;
}


Screeshot



Resources


Drupal Form API Reference - managed_file
Drupal API - function file_validate_extensions
I was able to resolve the issue using the solution posted here.

As I understand it, the issues is caused by an ID being used more than once. To fix this, you can implement an #after_build callback that ensures the upload fields will have unique IDs.

To summarize...

Add an #after_build callback to the managed_file field:

$num_docs = 3;

// Build the number of name fieldsets indicated by $form_state['num_docs'].
for ($i = 1; $i &lt;= $num_docs; $i++) {
  $form['managed_file'][$i] = array(
    '#type' =&gt; 'managed_file',
    '#title' =&gt; 'Managed File' . $i,
    '#progress_indicator' =&gt; 'throbber',
    '#progress_message' =&gt; 'Upload successful!',
    "#upload_validators"  =&gt; array("file_validate_extensions" =&gt; array("doc")),
    '#upload_location' =&gt; 'public://doc/',
    '#after_build' =&gt; array("MODULE_file_managed_fix_duplicate_id"),
  );
}

$form['submit'] = array(
  '#type' =&gt; 'submit',
  '#value' =&gt; t('Submit'),
);


Create the following callback:

function MODULE_file_managed_fix_duplicate_id($element) {
  if ($element['#id'] === $element['upload']['#id']) {
    $element['#id'] = drupal_html_id($element['#id']);
  }
  return $element;
}


Once I did that and cleared all my caches, the javascript errors went away and the error messages starting working.