Posted by JuliaKM on July 6, 2009 at 6:34pm
I added a word custom count validation function to a CCK field using #element_validate and am running into problems. The correct error message shows up when someone submits the form with too many words. However, this doesn't seem to be preventing the form from submitting. Here's my code. I would really, really appreciate any help you can offer.
<?php
/**
* Implementation of hook_form_alter().
*
* The function is named form_overrides_form_alter.
*/
function form_overrides_form_alter(&$form, $form_state, $form_id) {
$long_test_fields = array('field_admin_finance','field_campus_operations','field_ed_research','field_abstract');
foreach ($long_test_fields as $key => $field) {
$form[$field]['#element_validate'] = array(_count_words);
$form[$field]['#word_count'] = array('500'); //passing made up value with word count
}
}
function _count_words($element, &$form_state){
$value = $element[0]['#value']['value'];//grab the value of the field
$value_word_count = $element['#word_count'][0];//grab the set character count for the field
$value = strip_tags($value);
$pattern = "/[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-\-|:|\&|@)]+/";
$value = preg_replace ($pattern, " ", $value);
$value = str_replace(" - ", '',$value);
$value = trim($value);
$total_words = count(explode(" ",$value));
// dsm($total_words);
$label = $element[0]['#title'];
//If there's no match, send an error
if ($total_words > $value_word_count){
form_set_error($element, t("You have entered $total_words words. Please enter less than $value_word_count words in $label."));
}
}<?php>
Comments
The last time I had
The last time I had form_set_error issues it was because it didn't like my first param ($element here).
So, does the red box appear with the text in it (You have entered...)? Are you sure that $element is a non-empty string?
Ken Winters
www.coalmarch.com
Ken Winters
form_set_text
All of the element details are displaying correctly in the error message, which makes it even more confusing. It seems like all the data is passing perfectly to the validation function.
Hrm, it looks like you may
Hrm, it looks like you may actually need to call form_error not form_set_error. The form_set_error function expects a string, but $element is an array. The form_error function is a wrapper that handles this distinction in a very confusing way.
Edit: example_element.module has a real-world example of something very similar to what you want to do, and uses form_error.
Ken Winters
www.coalmarch.com
Ken Winters
Thanks!
It worked!!! Thank you so much! I owe you a beer/soda/other beverage of choice.
The documentation is definitely lacking. Here's the form_error doc:
http://api.drupal.org/api/function/form_error/6
And, here's the form_set_error doc:
http://api.drupal.org/api/function/form_set_error/6