Skip to content

Instantly share code, notes, and snippets.

@cmcintosh
Created May 20, 2016 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmcintosh/77e4cc4d5f0ef4bcb3d7cb3083a432aa to your computer and use it in GitHub Desktop.
Save cmcintosh/77e4cc4d5f0ef4bcb3d7cb3083a432aa to your computer and use it in GitHub Desktop.
buildForm Example
$form['username'] = array(
'#type' => 'textfield',
'#title' => t('Username'),
'#ajax' => [
'callback' => '::validateEmailAjax',
'event' => 'change',
],
'#suffix' => '<span class="username-available"></span>'
);
public function validateEmailAjax(array &$form, FormStateInterface $form_state) {
$available = $this->validateUsername($form, $form_state); // returns back boolean.
$response = new AjaxResponse();
$css = '';
if ($available) {
$css = "<style>.username-available { border: 1px solid green; }</style>";
$message = t('This username is available.');
}
else {
$css = "<style>.username-available { border: 1px solid red; }</style>";
}
$response->addCommand(new CssCommand('#edit-username', $css));
$response->addcommand(new HtmlCommand('.username-available', $message));
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment