0

Use case: I'm presenting the User with two Select Lists populated with the same People names.

The first select list is Primary Person, the second select list is Backup Person.

The User must select a different value from each list. The same Person can't be a primary and backup. If the User attempts to save the page using the same value, Drupal will throw an error.

What's the best approach?

2

For the Drupal form API, this would be handled with your validation handler. Have it check your 2 form values for equality, and throw an error if so.

function MYFORMBUILDER_validate($form, $form_state) {
  if($form_state['values']['person_primary'] == $form_state['values']['person_backup']) {
    form_set_error('person_primary', t('The primary and backup person must be different'));
    form_set_error('person_backup', t('The primary and backup person must be different'));
    array_pop($_SESSION['messages']['error']); //Remove duplicate message
  }
}
6
  • 2
    He may also need hook_form_alter() to add his custom validate handler to the existing node form first in the right order.
    – leymannx
    Sep 28 '15 at 20:32
  • Yeah, this answer assumes a custom form. If it's created by another module you'll need hook_form_alter().
    – Shawn Conn
    Sep 28 '15 at 20:35
  • Ok, thanks for the feedback. Should I put this in a Block with PHP filter, or in a custom module? Sep 29 '15 at 13:50
  • Custom module. A validation handler would not work embedded in a PHP filter block.
    – Shawn Conn
    Sep 29 '15 at 15:22
  • Ok. So If I understand all of comments - I will be creating a custom module, using hook_form_alter, and the above function ? Sep 29 '15 at 15:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.