rc-1.0.x-dev/src/Form/RcSettingsForm.php
src/Form/RcSettingsForm.php
<?php
namespace Drupal\rc\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use ATDev\RocketChat\Chat;
/**
* Class RcSettingsForm.
*/
class RcSettingsForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'rc.settings',
];
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'rc_settings';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Getting the RC Settings from saved configurations.
$config = $this->config('rc.settings');
$form['server'] = [
'#type' => 'textfield',
'#title' => $this->t('Server URL'),
'#description' => $this->t('The URL of your Rocket Chat server'),
'#required' => TRUE,
'#maxlength' => 255,
'#size' => 64,
'#default_value' => $config->get('access.server'),
];
$form['user'] = [
'#type' => 'textfield',
'#title' => $this->t('Rocket Chat admin username'),
'#description' => $this->t('The rocket chat admin username'),
'#required' => TRUE,
'#maxlength' => 64,
'#size' => 64,
'#default_value' => $config->get('access.user'),
];
$form['secret'] = [
'#type' => 'password',
'#title' => $this->t('Rocket Chat admin password'),
'#description' => $this->t('The password of the rocket chat admin'),
'#required' => TRUE,
'#maxlength' => 255,
'#size' => 64,
'#default_value' => $config->get('access.secret'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
// Set the Rocket Chat server URL.
$rcURL = $form_state->getValue('server');
// Remove forward shashed from the end of the URL.
$rcURL = rtrim($rcURL, "/");
// Try login with the current credentials.
$rcUser = $form_state->getValue('user');
$rcPassword = $form_state->getValue('secret');
Chat::setUrl($rcURL);
$result = Chat::login($rcUser, $rcPassword);
if (!$result) {
$form_state->setErrorByName('server', 'The provided credentials are not valid, please check them and try again');
$form_state->setErrorByName('user', 'The provided credentials are not valid, please check them and try again');
$form_state->setErrorByName('secret', 'The provided credentials are not valid, please check them and try again');
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
$this->config('rc.settings')
->set('access.server', rtrim($form_state->getValue('server')))
->set('access.user', $form_state->getValue('user'))
->set('access.secret', $form_state->getValue('secret'))
->save();
}
}
