1

I want to alter field widget item form of a file field with cardinality > 1 so that a new form element is added to each row of the file tables. For example, in the attached image, I want to add another text field below the "Description" for each uploaded file, even the one done via Ajax, not just the existing ones. I used hook_field_widget_form_alter() but it doesn't seem to work with the newly uploaded file. Any ideas?

File field table

1 Answer 1

0

A lot of the build logic for the file field widgets is handled in #process callbacks, so some detailed structures of each individual file's form element aren't really available during hook_form_alter()s.

You might want to preprocess the individual elements with hook_preprocess_file_widget(). Something like:

/**
 * Implements hook_preprocess_file_widget().
 */
function MYMODULE_preprocess_file_widget(&$vars) {
  // Make some alterations to normal file-field widgets.
  $element = &$vars['element'];
  if (isset($element['#file']) && is_object($element['#file'])) {
    // This is an existing file... alter $element accordingly.
  }
  else {
    // This is the actual upload widget... you may want to skip this or alter
    // it in a special way.
  }
}

You could also use hook_preprocess_file_widget_multiple() to specifically target a group of files in a file field that has cardinality > 1. In this case you may need to have some iteration logic to loop through the children elements with element_children().

1
  • For image fields, the hook is MYMODULE_preprocess_image_widget(&$vars) {}
    – Juampy NR
    Aug 17, 2015 at 19: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.