You are here

public function drupalchatSettingsForm::validateForm in DrupalChat 8

Form validation handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormBase::validateForm

File

src/Form/drupalchatSettingsForm.php, line 263
Contains Drupal\drupalchat\Form\drupalchatSettingsForm

Class

drupalchatSettingsForm
Class drupalchatSettingsForm

Namespace

Drupal\drupalchat\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);

  // Load the current user.
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()
    ->id());
  $user_name = $user
    ->getUsername();
  if ($form_state
    ->getValue('drupalchat_polling_method') == DRUPALCHAT_COMMERCIAL) {
    $drupalchat_api_key = trim($form_state
      ->getValue('drupalchat_external_api_key'));
    $drupalchat_app_id = trim($form_state
      ->getValue('drupalchat_app_id'));
    $formValues = array(
      'api_key' => $drupalchat_api_key,
      'app_id' => $drupalchat_app_id,
    );
    $response = drupalchatController::_drupalchat_get_auth($formValues);
    if (!array_key_exists('key', $response)) {
      $form_state
        ->setErrorByName('drupalchat_external_api_key', "Unable to connect to iFlyChat server. Error code - " . $response['code'] . ". Error message - " . $response['error'] . ".");
    }
    if (!$drupalchat_app_id) {

      //check if app id is empty.
      $form_state
        ->setErrorByName('drupalchat_app_id', t("Please Enter APP ID."));
    }
    if (!(strlen($drupalchat_app_id) == 36 && $drupalchat_app_id[14] == '4')) {
      $form_state
        ->setErrorByName('drupalchat_app_id', t("Invalid APP ID."));
    }
    if (!$drupalchat_api_key) {
      $form_state
        ->setErrorByName('drupalchat_external_api_key', t('Please enter API key.'));
    }
  }
  if ($form_state
    ->getValue('drupalchat_rel') == DRUPALCHAT_REL_UR) {
    if ($form_state
      ->getValue('drupalchat_rel')) {
      $array = drupal_explode_tags($form_state
        ->getValue('drupalchat_rel'));
      $error = array();
      foreach ($array as $key) {
        if (!db_query("SELECT COUNT(*) FROM {user_relationship_types} WHERE name = :name", array(
          ':name' => $key,
        ))
          ->fetchField()) {
          $error[] = $key;
        }
      }
      if (!empty($error)) {
        $form_state
          ->setErrorByName('drupalchat_ur_name', t('User Relationship type %type was not found.', array(
          '%type' => drupal_implode_tags($error),
        )));
      }
    }
  }
}