How to make filefield image required via form_alter?
Hunabku - November 8, 2009 - 22:30
| Project: | FileField |
| Version: | 6.x-3.1 |
| Component: | Code |
| Category: | support request |
| Priority: | normal |
| Assigned: | Unassigned |
| Status: | closed |
Jump to:
Description
Well i tried setting a bunch of $form required properties for my cck image field in after_build -> to no avail.
I did get the style to show the required * asterisks, but required validation is not triggered.
any ideas?

#1
File fields in Drupal do not support #required (this applies to all #type => 'file', not just those provided by FileField). It's a bug in Drupal core that has existed since Drupal 4.7. FileField works around this by providing it's own validation on the node form that does this checking manually. The only way to add your own required validation for different FileFields is to make another validation handler to the node form, then check if the field has a value.
So in short you'll need to add
$form['#validate'][] = 'mymodule_node_form_validate'in your hook_form_alter(). Then see the filefield_node_form_validate() function in filefield_widget.inc and see how it returns a validation error if a file is not uploaded.#2
Thanks quicksketch - starting with your instructions i came up with the simplest route that works for me.
in mymodule_form_alter function
//at the end of form_alter i always put an after_build to handle cck fields, etc.$form['#after_build'][] = 'mymodule_after_build';
in mymodule_after_build function
//inside corresponding form id test statement goes the following two lines of code$form['#validate'][] = 'mymodule_validate_image';
$form['field_myimage'][0]['#required'] = TRUE; // So the "required" asterisks shows up
//at the end of after_build remember to return $form
return $form;
also in mymodule
function mymodule_validate_image ($form, &$form_state) {if (!$form_state['values']['field_myimage'][0]['fid']) {
form_set_error('field_myimage', t('Please choose a file to upload.'));
}
}
#3
Looks great to me! Marking this as fixed.
#4
Automatically closed -- issue fixed for 2 weeks with no activity.