Commit 9e84e874 authored by Gorodkov Denis's avatar Gorodkov Denis

Form Ajax

parent 2807af60
...@@ -43,3 +43,4 @@ function mymodule_schema() { ...@@ -43,3 +43,4 @@ function mymodule_schema() {
function mymodule_uninstall() { function mymodule_uninstall() {
\Drupal::state()->delete('mymodule.AAA_custom_table'); \Drupal::state()->delete('mymodule.AAA_custom_table');
} }
...@@ -91,3 +91,12 @@ function mymodule_preprocess(&$variables, $hook) { ...@@ -91,3 +91,12 @@ function mymodule_preprocess(&$variables, $hook) {
$variables["#cache"]["contexts"][] = "url.query_args"; $variables["#cache"]["contexts"][] = "url.query_args";
} }
} }
/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_mymodule_ajax_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
#$form["url"]["#required"] = false;
#
}
...@@ -3,10 +3,15 @@ ...@@ -3,10 +3,15 @@
namespace Drupal\mymodule\Form; namespace Drupal\mymodule\Form;
use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Ajax\CssCommand; use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand; use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Url;
use Drupal\redirect\Entity\Redirect;
class AjaxForm extends FormBase { class AjaxForm extends FormBase {
public function getFormId() { public function getFormId() {
...@@ -29,16 +34,15 @@ class AjaxForm extends FormBase { ...@@ -29,16 +34,15 @@ class AjaxForm extends FormBase {
'#prefix' => '', '#prefix' => '',
'#suffix' => '<div class="email-validation-message"></div>', '#suffix' => '<div class="email-validation-message"></div>',
'#ajax' => [ '#ajax' => [
'callback' => [$this, 'validateEmailCallbackAjax'], 'callback' => [$this, 'validateEmailCallbackAjax'],
'event' => 'change', 'event' => 'change',
'wrapper' => 'edit-email', 'wrapper' => 'edit-email',
], ],
); );
$form['url'] = array( $form['url'] = array(
'#type' => 'textfield', '#type' => 'textfield',
'#title' => 'URL', '#title' => 'URL',
'#required' => TRUE,
'#prefix' => '', '#prefix' => '',
'#suffix' => '<div class="url-validation-message"></div>', '#suffix' => '<div class="url-validation-message"></div>',
'#ajax' => [ '#ajax' => [
...@@ -46,20 +50,96 @@ class AjaxForm extends FormBase { ...@@ -46,20 +50,96 @@ class AjaxForm extends FormBase {
'event' => 'change', 'event' => 'change',
'wrapper' => 'edit-email', 'wrapper' => 'edit-email',
], ],
'#states' => array(
'visible' => array(
':input[name="site"]' => ['value' => 'hasSite'],
),
),
);
$form['site'] = array(
'#type' => 'radios',
'#description' => t('Select'),
'#attributes' => [
'name' => 'site'
],
'#default_value' => 'noSite',
'#required' => TRUE,
'#options' => array(
'hasSite' => t('У меня есть сайт'),
'noSite' => t('У меня нету сайта'),
)
); );
$form['submit'] = array( $form['submit'] = array(
'#type' => 'submit', '#type' => 'submit',
'#value' => 'Click', '#value' => 'Click',
'#ajax' => [
'callback' => [$this, 'alert'],
'event' => 'click',
],
); );
return $form; return $form;
} }
public function validateForm(array &$form, FormStateInterface $form_state) { public function validateForm(array &$form, FormStateInterface $form_state) {
$url = $form_state->getValue('url');
$email = $form_state->getValue('email');
$site = $form_state->getValue('site');
if ($site == 'hasSite') {
if (!$this->checkUrl($url) or empty($url)) {
$form_state->setErrorByName('url', 'Неверно введен url');
}
}
if (!$this->checkEmail($email)) {
$form_state->setErrorByName('email', 'Неверно введен email');
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
#$url = Url::fromRoute('mymodule.batch_form');
#$form_state->setRedirectUrl();
#$form_state->setRedirect();
$url = $form_state->getValue('url'); $query = \Drupal::database()->insert('AAA_custom_table');
$query->fields([
'name' => $form_state->getValue('name'),
'email' => $form_state->getValue('email'),
'url' => $form_state->getValue('url'),
]);
$query->execute();
$form_state->setRedirect('<front>');
}
public function getResponse(array &$form, FormStateInterface $form_state, $field_name) {
$response = new AjaxResponse();
$val = $field_name == 'email' ? $val = $form_state->getValue('email') : $val = $form_state->getValue('url');
$check = $field_name == 'email' ? $check = 'checkEmail' : $check = 'checkUrl';
if (!$this->$check($val)) {
$response->addCommand(new HtmlCommand('.email-validation-message', "Введен не корректный $field_name"));
$response->addCommand(new CssCommand('.email-validation-message', ['color' => 'red']));
$response->addCommand(new CssCommand('#edit-email', ['border' => '1px solid red']));
} else {
$response->addCommand(new HtmlCommand('.email-validation-message', ''));
$response->addCommand(new CssCommand('#edit-email', ['border' => '']));
}
return $response;
}
public function validateEmailCallbackAjax(array &$form, FormStateInterface $form_state, $filed_name) {
$field_name = 'email';
$response = $this->getResponse($form, $form_state, $field_name);
return $response;
}
public function validateUrlCallbackAjax(array &$form, FormStateInterface $form_state) {
$field_name = 'url';
$response = $this->getResponse($form, $form_state, $field_name);
return $response;
}
public function checkUrl($url) {
$regexp = '/^(https|http):\/\//'; $regexp = '/^(https|http):\/\//';
$checkHttp = (bool)preg_match($regexp, $url); $checkHttp = (bool)preg_match($regexp, $url);
if ($checkHttp) { if ($checkHttp) {
...@@ -78,38 +158,39 @@ class AjaxForm extends FormBase { ...@@ -78,38 +158,39 @@ class AjaxForm extends FormBase {
$url = explode('.',$url); $url = explode('.',$url);
$url = $url[0] . '.' . $url[1]; $url = $url[0] . '.' . $url[1];
if ($checkUrl) {
} return true;
} else {
public function submitForm(array &$form, FormStateInterface $form_state) { return false;
$query = \Drupal::database()->insert('AAA_custom_table'); }
$query->fields([
'name' => $form_state->getValue('name'),
'email' => $form_state->getValue('email'),
'url' => $form_state->getValue('url'),
]);
$query->execute();
} }
public function validateEmailCallbackAjax(array &$form, FormStateInterface $form_state) { public function checkEmail($email) {
$response = new AjaxResponse();
$email = $form_state->getValue('email');
$email_valid = filter_var($email, FILTER_VALIDATE_EMAIL); $email_valid = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email_valid and !empty($email)) { if ($email_valid and !empty($email)) {
$response->addCommand(new HtmlCommand('.email-validation-message', 'Введен не корректный email')); return true;
$response->addCommand(new CssCommand('.email-validation-message', ['color' => 'red']));
$response->addCommand(new CssCommand('#edit-email', ['border' => '1px solid red']));
} else { } else {
$response->addCommand(new HtmlCommand('.email-validation-message', '')); return false;
$response->addCommand(new CssCommand('#edit-email', ['border' => '']));
} }
return $response;
} }
public function alert(array &$form, FormStateInterface $form_state) {
public function validateUrlCallbackAjax(array &$form, FormStateInterface $formState) {
$response = new AjaxResponse(); $response = new AjaxResponse();
$response->addCommand(new HtmlCommand('.url-validation-message', 'ZXC')); $url = $form_state->getValue('url');
$response->addCommand(new CssCommand('#edit-url', ['border' => '1px solid red'])); $email = $form_state->getValue('email');
$site = $form_state->getValue('site');
$commandRedirect = new RedirectCommand('/home');
if ($site == 'hasSite') {
if (!$this->checkUrl($url) or empty($url)) {
$form_state->setErrorByName('url', 'Неверное введен url');
}
}
if (!$this->checkEmail($email)) {
$form_state->setErrorByName('email', 'Неверное введен email');
}
$response->addCommand(new AlertCommand('Спасибо за заполнение'));
$response->addCommand($commandRedirect);
return $response; return $response;
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment