2

I have a custom validator on a webform. When a person enters an address, I validate it. When the address is not right, I set an error in the validation function. This is all going well. But now I want to give the visitor suggestions when he enter a wrong address. This should be done by giving the suggestion in a markup underneath the address input.

I allready set up an empty markup field in the webform, now I just want to put information in it during validation. How is this possible. If you need any dpm or printout let me know please.

Thanks in advance.

1 Answer 1

2

In your validate you can set a variable in the $form_state that tells if the validation failed or not:

function webform_validate_handler(&$form, &$form_state) {
  if ($mail_invalid) {
    $form_state['mail_invalid'] = TRUE;
  }
  else {
    $form_state['mail_invalid'] = FALSE;
  }
}

Then in your form, you can check for empty($form_state['mail_invalid']) and show the markup when the empty check returns false.

function hook_form_alter(&$form, &$form_state, $form_id) {
  ...
  if (!empty($form_state['mail_invalid']) {
    $form['markup'] = ...;
  }
}
7
  • how can I alter the form then ? hook_form_alter is called BEFORE validation handler, and if I change any varible in $form in the validation hook, nothing happens.
    – Nealv
    Commented Mar 18, 2012 at 18:56
  • @Nealv You didn't read my answer properly, I have updated my answer to clearly show what I'm talking about. You need to check $form_state like I explained.
    – googletorp
    Commented Mar 18, 2012 at 20:21
  • I understand what you are saying, but the "validation" hook is called AFTER the form alter. so when the form_alter is executed, $form_state['mail_invalid'] will be NULL, because you set it afterwards. right
    – Nealv
    Commented Mar 18, 2012 at 22:40
  • @Nealv That is why you use the empty() to check it. First time around it won't exist so !empty() == FALSE in order words the markup isn't added to the form. If the validation fails, the form is rebuild, but this time !empty() == TRUE so the markup is shown. This is really quite simple.
    – googletorp
    Commented Mar 19, 2012 at 12:22
  • I understand what you are saying, but there is no first and second time. flow is like this: hook_form_alter -> hook_validate -> render. So after the validation I cant change anything in the form, and during neither because the form is not a reference but a copy. Is it possible to chat ?
    – Nealv
    Commented Mar 19, 2012 at 15:17

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.