0

This is an extension of this question:

Need help with AJAX callback function for text field validation in form_alter

I have a form with a Username autocomplete field (txn_user). The editors want to be able to enter a UID (txn_userid) as an alternative way of specifying the User for the form. They want to be able to enter the UID and skip the Username field altogether.

So in my form validation function, I want to be able to disable the required property (and all other validation) of the Username field during a Submit IF the editor typed in a UID field. In other words: the UID field should 'short-circuit' the Username field.

This is what I have so far (which doesn't work, obviously). Or do I need to do this via AJAX or straight JS?

function _validate_add_userpoints_userid(&$form, &$form_state) {
    $values = $form_state['values'];
    if( $values['txn_userid'] ) {
        $newuser = user_load($values['txn_userid']);
        if( ! $newuser) {
          form_set_error('txn_userid', 'You have entered an invalid UID. Either leave this blank and select a Username or enter a valid UID');          
    }
    else {  
        // this part works... the User Name is properly assigned.
        $form['txn_user']['#value'] = $newuser->name;       
        $form_state['values']['txn_user'] = $newuser; 
        $form_state['input']['txn_user'] = $newuser->name;          

        // this part doesn't work... the User Name field is still required on submit.
        $form['txn_user']['#disabled'] = TRUE;
        $form['txn_user']['#ajax_processed'] = TRUE;
        $form['txn_user']['#required'] = FALSE;
        $form['txn_user']['#needs_validation'] = FALSE;         
        unset($form['txn_user']['#process']);
    }
}

}

1

1 Answer 1

0

Why dont you use conditional field module?

https://www.drupal.org/project/conditional_fields

By this module you can disable the requirement of fields when something happens to another field. you can also implement your form as a content type so its node/add page will be your form. Then by using the different hooks you can add autocomplete field or do any thing else

2
  • Thanks, I'll take a look. I'd -rather- just have code to do this one small thing. The site is pretty well 'done' and I hate adding new modules for just one thing. For small things, I much prefer just having one bit of well-commented code in MY_MODULE. Seems easier for management.
    – jchwebdev
    Commented Apr 10, 2015 at 22:03
  • This module is very tiny and it is more reasonable to reuse the codes that their safety and well performance are already tested and proved.
    – M a m a D
    Commented Apr 11, 2015 at 1:48

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.