I have an existing form with a User field $txn_user for capturing the User by name using the standard autocomplete. So I guess that's a User object, right?
We have many thousands of users and the data entry people would like to -also- be able to enter just the UID (which they have memorised in many cases). So I need a UID field which has an ajax validation to lookup the user by UID and then, update the UserName field.
So in MYMODULE_myform_alter()...
$form['container'] = array(
'#prefix' => '<div id="example_form_wrapper">',
'#suffix' => '</div>',
);
$form ['#validate'][] = '_validate_add_userpoints_userid';
$form['txn_userid'] = array(
'#type' => 'textfield',
'#title' => 'UID',
'#size' => 4,
'#maxlength' => 4,
'#default_value' => isset($txn_user) ? $txn_user->uid : '',
'#description' => 'The User ID',
'#required' => TRUE,
'#weight' => -15,
'#disabled' => FALSE,
'#ajax' => array(
'callback' => 'validate_uid_ajax_callback',
'wrapper' => 'example_form_wrapper',
),
);
...and then the field validation callback function
function validate_uid_ajax_callback(&$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 {
$form['txn_user']['#value'] = $newuser->name;
$form_state['values']['txn_user'] = $newuser;
$form_state['input']['txn_user'] = $newuser->name;
}
}
}
So the ajax spinner goes off and $form gets updated. $form_state does not.
But I can't figure out how do I set the value of the txn_user and txn_user->uid (the fields in the form so they update dynamically)?
Now... if this helps, here is my $form validate function. This -works-. So the only issue is that users (reasonably) expect that when they update the UID field, the User name will update.
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 {
$form['txn_user']['#value'] = $newuser->name;
$form_state['values']['txn_user'] = $newuser;
$form_state['input']['txn_user'] = $newuser->name;
}
}
}
TIA,