Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.02 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Drupal\hello\Form;
  4.  
  5. use Drupal\Component\Datetime\TimeInterface;
  6. use Drupal\Core\Form\FormBase;
  7. use Drupal\Core\Form\FormStateInterface;
  8. use Drupal\Core\Ajax\AjaxResponse;
  9. use Drupal\Core\Ajax\CssCommand;
  10. use Drupal\Core\Ajax\HtmlCommand;
  11. use Drupal\Core\State\StateInterface;
  12. use Symfony\Component\DependencyInjection\ContainerInterface;
  13.  
  14. /**
  15. * Implements a calculator form.
  16. */
  17. class HelloCalculator extends FormBase {
  18.  
  19. protected $state;
  20. protected $time;
  21.  
  22. /**
  23. * {@inheritdoc}.
  24. */
  25. public function __construct(StateInterface $state, TimeInterface $time) {
  26. $this->state = $state;
  27. $this->time = $time;
  28. }
  29.  
  30. /**
  31. * {@inheritdoc}.
  32. */
  33. public static function create(ContainerInterface $container) {
  34. return new static(
  35. $container->get('state'),
  36. $container->get('datetime.time')
  37. );
  38. }
  39.  
  40. /**
  41. * {@inheritdoc}.
  42. */
  43. public function getFormID() {
  44. return 'hello_calculator';
  45. }
  46.  
  47. /**
  48. * {@inheritdoc}.
  49. */
  50. public function buildForm(array $form, FormStateInterface $form_state) {
  51. // Champ destiné à afficher le résultat du calcul.
  52. if (isset($form_state->getRebuildInfo()['result'])) {
  53. $form['result'] = [
  54. '#markup' => '<h2>' . $this->t('Result: ') . $form_state->getRebuildInfo()['result'] . '</h2>',
  55. ];
  56. }
  57.  
  58. $form['value1'] = [
  59. '#type' => 'textfield',
  60. '#title' => $this->t('First value'),
  61. '#description' => $this->t('Enter first value.'),
  62. '#required' => TRUE,
  63. '#default_value' => '2',
  64. '#ajax' => [
  65. 'callback' => [$this, 'AjaxValidateNumeric'],
  66. 'event' => 'keyup',
  67. ],
  68. '#prefix' => '<span id="error-message-value1"></span>',
  69. ];
  70. $form['operation'] = [
  71. '#type' => 'radios',
  72. '#title' => $this->t('Operation'),
  73. '#description' => $this->t('Choose operation for processing.'),
  74. '#options' => [
  75. 'addition' => $this->t('Add'),
  76. 'soustraction' => $this->t('Soustract'),
  77. 'multiplication' => $this->t('Multiply'),
  78. 'division' => $this->t('Divide'),
  79. ],
  80. '#default_value' => 'addition',
  81. ];
  82. $form['value2'] = [
  83. '#type' => 'textfield',
  84. '#title' => $this->t('Second value'),
  85. '#description' => $this->t('Enter second value.'),
  86. '#required' => TRUE,
  87. '#default_value' => '2',
  88. '#ajax' => [
  89. 'callback' => [$this, 'AjaxValidateNumeric'],
  90. 'event' => 'keyup',
  91. ],
  92. '#prefix' => '<span id="error-message-value2"></span>',
  93. ];
  94. $form['view'] = [
  95. '#type' => 'select',
  96. '#title' => $this->t('View result on...'),
  97. '#description' => $this->t('Choose operation for processing.'),
  98. '#options' => [
  99. 'redirect' => $this->t('...a redirect page'),
  100. 'rebuild' => $this->t('...form'),
  101. ],
  102. '#default_value' => 'redirect',
  103. ];
  104. $form['submit'] = [
  105. '#type' => 'submit',
  106. '#value' => $this->t('Calculate'),
  107. ];
  108.  
  109. return $form;
  110. }
  111.  
  112. /**
  113. * @param array $form
  114. * @param \Drupal\Core\Form\FormStateInterface $form_state
  115. * @return \Drupal\Core\Ajax\AjaxResponse
  116. */
  117. public function AjaxValidateNumeric(array &$form, FormStateInterface $form_state) {
  118. $response = new AjaxResponse();
  119.  
  120. $field = $form_state->getTriggeringElement()['#name'];
  121.  
  122. if (is_numeric($form_state->getValue($field))) {
  123. $css = ['border' => '2px solid green'];
  124. $message = $this->t('OK!');
  125. } else {
  126. $css = ['border' => '2px solid red'];
  127. $message = $this->t('%field must be numeric!', ['%field' => $form[$field]['#title']]);
  128. }
  129.  
  130. $response->AddCommand(new CssCommand("[name=$field]", $css));
  131. $response->AddCommand(new HtmlCommand('#error-message-' . $field, $form_state->getTriggeringElement()['#id']));
  132.  
  133. return $response;
  134. }
  135.  
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function validateForm(array &$form, FormStateInterface $form_state) {
  140. $value_1 = $form_state->getValue('value1');
  141. $value_2 = $form_state->getValue('value2');
  142. $operation = $form_state->getValue('operation');
  143.  
  144. if (!is_numeric($value_1)) {
  145. $form_state->setErrorByName('value1', $this->t('First value must be numeric!'));
  146. }
  147. if (!is_numeric($value_2)) {
  148. $form_state->setErrorByName('value2', $this->t('Second value must be numeric!'));
  149. }
  150. if ($value_2 == '0' && $operation == 'division') {
  151. $form_state->setErrorByName('value2', $this->t('Cannot divide by zero!'));
  152. }
  153.  
  154. // if (isset($form['result'])) {
  155. // unset($form['result']);
  156. // }
  157. }
  158.  
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function submitForm(array &$form, FormStateInterface $form_state) {
  163. //kint($form_state);
  164. // Récupère la valeur des champs.
  165. $value_1 = $form_state->getValue('value1');
  166. $value_2 = $form_state->getValue('value2');
  167. $operation = $form_state->getValue('operation');
  168. $view = $form_state->getValue('view');
  169.  
  170. $resultat = '';
  171. switch ($operation) {
  172. case 'addition':
  173. $resultat = $value_1 + $value_2;
  174. break;
  175. case 'soustraction':
  176. $resultat = $value_1 - $value_2;
  177. break;
  178. case 'multiplication':
  179. $resultat = $value_1 * $value_2;
  180. break;
  181. case 'division':
  182. $resultat = $value_1 / $value_2;
  183. break;
  184. }
  185.  
  186. // Redirection vers la route "hello.calculator.result".
  187. if ($view == 'redirect') {
  188. // On passe le résultat en paramètre dans l'url.
  189. $form_state->setRedirect('hello.calculator.result', ['result' => $resultat]);
  190. }
  191.  
  192. // On affiche le résultat dans le formulaire.
  193. if ($view == 'rebuild') {
  194. // On passe le résultat.
  195. $form_state->addRebuildInfo('result', $resultat);
  196. // Reconstruction du formulaire avec les valeurs saisies.
  197. $form_state->setRebuild();
  198. }
  199.  
  200. // Enregistrement de l'heure de soumission avec State API.
  201. $this->state->set('hello_form_submission_time', $this->time->getCurrentTime());
  202. }
  203.  
  204. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement