0

How to pass the custom validation after custom submission?

I have problem in getting a variable from a custom submit handler. Actually, the custom validation must happen in the last step in order to validate correctly.

Workflow is:

1.custom submit.

2.get a value from the API.

3.pass it to custom validation.

Since the custom validation step comes first, I am unable to validate it properly.

10
  • The simple answer is, you cannot. Validation always happens before submission, and there is no way around this. Why don't you extend your question to explain exactly what you are trying to do, rather than in general terms, and maybe we can help with a solution. – Jaypan Feb 12 '17 at 8:13
  • After I submit, I have to get a response from api and that will update a Drupal field. I have to validate the response based on the response from api and prevent form submission based if response from api is 0. – user3418540 Feb 12 '17 at 9:34
  • What API are you getting the value from? Why can't you get that value in your validation function? – Jaypan Feb 12 '17 at 10:33
  • So pass the same function in hook submit and hook validate – user3418540 Feb 12 '17 at 11:05
  • I don't understand. – Jaypan Feb 12 '17 at 11:36
1

You can use form_set_value() in your validation handler. Let's say you are retrieving a user ID from a remote API, by sending the user's name. In your form definition, you can have:

$form['user'] = array (
  '#type' => 'textfield',
  '#title' => t('User to fetch'),
);

In your validation handler, you can retrieve the value. If a value exists you save it using form_set_value, and if it doesn't, you set an error:

$remote_user_id = retrieve_uid_from_api($form_state['values']['user']);
if($remote_user_id) {
  form_set_value($form['user'], $remote_user_id);
}
else {
  form_set_error('user', t('%user does not exist in the remote API', array('%user' => $form_state['values']['user']));
}

So in your submit function, `$form_state['values']['user'] will now contain the User ID from the remote API:

$remote_user_id = $form_state['values']['user'];
1
  • Only one problem, after I submit to API it successfully goes there but sometimes it does not save in default drupal DB. Any suggestions – user3418540 Mar 30 '17 at 5:14

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.