FormValidationMessageOrderTest.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace Drupal\KernelTests\Core\Form;
  3. use Drupal\Core\Form\FormInterface;
  4. use Drupal\Core\Form\FormState;
  5. use Drupal\Core\Form\FormStateInterface;
  6. use Drupal\KernelTests\KernelTestBase;
  7. /**
  8. * Tests form validation mesages are displayed in the same order as the fields.
  9. *
  10. * @group Form
  11. */
  12. class FormValidationMessageOrderTest extends KernelTestBase implements FormInterface {
  13. /**
  14. * {@inheritdoc}
  15. */
  16. public function getFormId() {
  17. return 'form_validation_error_message_order_test';
  18. }
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function buildForm(array $form, FormStateInterface $form_state) {
  23. // Prepare fields with weights specified.
  24. $form['one'] = [
  25. '#type' => 'textfield',
  26. '#title' => 'One',
  27. '#required' => TRUE,
  28. '#weight' => 40,
  29. ];
  30. $form['two'] = [
  31. '#type' => 'textfield',
  32. '#title' => 'Two',
  33. '#required' => TRUE,
  34. '#weight' => 30,
  35. ];
  36. $form['three'] = [
  37. '#type' => 'textfield',
  38. '#title' => 'Three',
  39. '#required' => TRUE,
  40. '#weight' => 10,
  41. ];
  42. $form['four'] = [
  43. '#type' => 'textfield',
  44. '#title' => 'Four',
  45. '#required' => TRUE,
  46. '#weight' => 20,
  47. ];
  48. $form['actions'] = [
  49. '#type' => 'actions',
  50. 'submit' => [
  51. '#type' => 'submit',
  52. '#value' => 'Submit',
  53. ],
  54. ];
  55. return $form;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function validateForm(array &$form, FormStateInterface $form_state) {
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function submitForm(array &$form, FormStateInterface $form_state) {
  66. }
  67. /**
  68. * Tests that fields validation messages are sorted in the fields order.
  69. */
  70. public function testLimitValidationErrors() {
  71. $form_state = new FormState();
  72. $form_builder = $this->container->get('form_builder');
  73. $form_builder->submitForm($this, $form_state);
  74. $messages = drupal_get_messages();
  75. $this->assertTrue(isset($messages['error']));
  76. $error_messages = $messages['error'];
  77. $this->assertEqual($error_messages[0], 'Three field is required.');
  78. $this->assertEqual($error_messages[1], 'Four field is required.');
  79. $this->assertEqual($error_messages[2], 'Two field is required.');
  80. $this->assertEqual($error_messages[3], 'One field is required.');
  81. }
  82. }