Created
May 4, 2022 09:53
-
-
Save vishalbandre/3fba3831d9c64a7a5585a85f539172df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\vishal_ajax_api\Form; | |
use Drupal\Core\Form\FormBase; | |
use Drupal\Core\Form\FormStateInterface; | |
use Drupal\Core\Ajax\AjaxResponse; | |
use Drupal\Core\Ajax\HtmlCommand; | |
/** | |
* Implements an AjaxForm to test an Ajax sample. | |
*/ | |
class AjaxForm extends FormBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getFormId() { | |
return 'vishal_ajax_api_form'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function buildForm(array $form, FormStateInterface $form_state) { | |
$form['user_mail'] = [ | |
'#type' => 'textfield', | |
'#title' => $this->t('Email'), | |
'#description' => $this->t('Enter your email address'), | |
'#prefix' => $this->t('<div id="user-mail"></div>'), | |
'#ajax' => [ | |
'callback' => '::checkEmailValidation', | |
'effect' => 'fade', | |
'event' => 'change', | |
'progress' => [ | |
'type' => 'throbber', | |
'message' => NULL, | |
], | |
], | |
]; | |
return $form; | |
} | |
/** | |
* Checks email validation. | |
*/ | |
public function checkEmailValidation(array $form, FormStateInterface $form_state) { | |
$ajax_response = new AjaxResponse(); | |
// Check if email exists or not. | |
if (user_load_by_name($form_state->getValue('user_mail')) || user_load_by_mail($form_state->getValue('user_mail'))) { | |
$text = 'User or email exists.'; | |
} | |
else { | |
$text = 'User or email does not exists.'; | |
} | |
$ajax_response->addCommand(new HtmlCommand('#user-mail', $text)); | |
return $ajax_response; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment