You are here

public static function MobileNumber::verifyAjax in Mobile Number 8

Same name and namespace in other branches
  1. 2.0.x src/Element/MobileNumber.php \Drupal\mobile_number\Element\MobileNumber::verifyAjax()

Mobile number element ajax callback.

Parameters

array $complete_form: Complete form.

\Drupal\Core\Form\FormStateInterface $form_state: Form state.

Return value

\Drupal\Core\Ajax\AjaxResponse Ajax response.

File

src/Element/MobileNumber.php, line 388

Class

MobileNumber
Provides a form input element for entering an email address.

Namespace

Drupal\mobile_number\Element

Code

public static function verifyAjax($complete_form, FormStateInterface $form_state) {

  /** @var \Drupal\mobile_number\MobileNumberUtilInterface $util */
  $util = \Drupal::service('mobile_number.util');
  $element = static::getTriggeringElementParent($complete_form, $form_state);
  $tree_parents = $element['#parents'];
  $field_path = implode('][', $tree_parents);
  $storage = $form_state
    ->getStorage();
  $token = !empty($storage['mobile_number_fields'][$field_path]['token']) ? $storage['mobile_number_fields'][$field_path]['token'] : NULL;
  $element['verification_token']['#value'] = $token;
  $settings = $element['#mobile_number'];
  $op = static::getOp($element, $form_state);
  $errors = $form_state
    ->getErrors();
  foreach ($errors as $path => $message) {
    if (strpos($path, implode('][', $element['#parents'])) === 0) {
      $messenger = \Drupal::messenger();
      if (isset($message)) {
        $messenger
          ->addMessage($message, 'error');
      }
    }
    else {
      unset($errors[$path]);
    }
  }
  $mobile_number = static::getMobileNumber($element);
  $verified = FALSE;
  $verify_prompt = FALSE;
  if ($mobile_number) {
    $verified = static::isVerified($element);
    $verify_flood_ok = $verified || $util
      ->checkFlood($mobile_number);
    if ($verify_flood_ok) {
      if (!$verified && !$errors && $op == 'mobile_number_send_verification') {
        $verify_prompt = TRUE;
      }
      elseif (!$verified && $op == 'mobile_number_verify') {
        $verify_prompt = TRUE;
      }
    }
  }
  $element['messages'] = [
    '#type' => 'status_messages',
  ];
  unset($element['_weight']);
  $response = new AjaxResponse();
  $response
    ->addCommand(new ReplaceCommand(NULL, $element));
  $settings = [];
  if ($verify_prompt) {
    $settings['mobileNumberVerificationPrompt'] = $element['#id'];
  }
  else {
    $settings['mobileNumberHideVerificationPrompt'] = $element['#id'];
  }
  if ($verified) {
    $settings['mobileNumberVerified'] = $element['#id'];
  }
  if ($settings) {
    $response
      ->addCommand(new SettingsCommand($settings));
  }
  return $response;
}