diff --git a/core/includes/authorize.inc b/core/includes/authorize.inc index 481fd30..70fb4ca 100644 --- a/core/includes/authorize.inc +++ b/core/includes/authorize.inc @@ -210,7 +210,7 @@ function authorize_filetransfer_form_validate($form, &$form_state) { catch (Exception $e) { // The format of this error message is similar to that used on the // database connection form in the installer. - form_set_error('connection_settings', t('Failed to connect to the server. The server reports the following message: !message For more help installing or updating code on your server, see the handbook.', array( + form_set_error('connection_settings', $form_state, t('Failed to connect to the server. The server reports the following message: !message For more help installing or updating code on your server, see the handbook.', array( '!message' => '

' . $e->getMessage() . '

', '@handbook_url' => 'http://drupal.org/documentation/install/modules-themes', ))); diff --git a/core/includes/form.inc b/core/includes/form.inc index 5867a36..726cf2d 100644 --- a/core/includes/form.inc +++ b/core/includes/form.inc @@ -274,8 +274,8 @@ function form_execute_handlers($type, &$form, &$form_state) { * * @deprecated as of Drupal 8.0. Use \Drupal::formBuilder()->setErrorByName() */ -function form_set_error($name = NULL, $message = '', $limit_validation_errors = NULL) { - return \Drupal::formBuilder()->setErrorByName($name, $message, $limit_validation_errors); +function form_set_error($name, array &$form_state, $message = '') { + \Drupal::formBuilder()->setErrorByName($name, $form_state, $message); } /** @@ -283,8 +283,8 @@ function form_set_error($name = NULL, $message = '', $limit_validation_errors = * * @deprecated as of Drupal 8.0. Use \Drupal::formBuilder()->clearErrors() */ -function form_clear_error() { - \Drupal::formBuilder()->clearErrors(); +function form_clear_error(array &$form_state) { + \Drupal::formBuilder()->clearErrors($form_state); } /** @@ -292,8 +292,8 @@ function form_clear_error() { * * @deprecated as of Drupal 8.0. Use \Drupal::formBuilder()->getErrors() */ -function form_get_errors() { - return \Drupal::formBuilder()->getErrors(); +function form_get_errors(array &$form_state) { + return \Drupal::formBuilder()->getErrors($form_state); } /** @@ -301,8 +301,8 @@ function form_get_errors() { * * @deprecated as of Drupal 8.0. Use \Drupal::formBuilder()->getError() */ -function form_get_error($element) { - return \Drupal::formBuilder()->getError($element); +function form_get_error($element, array &$form_state) { + return \Drupal::formBuilder()->getError($element, $form_state); } /** @@ -310,8 +310,8 @@ function form_get_error($element) { * * @deprecated as of Drupal 8.0. Use \Drupal::formBuilder()->setError() */ -function form_error(&$element, $message = '') { - \Drupal::formBuilder()->setError($element, $message); +function form_error(&$element, array &$form_state, $message = '') { + \Drupal::formBuilder()->setError($element, $form_state, $message); } /** @@ -1131,11 +1131,11 @@ function password_confirm_validate($element, &$element_state) { $pass2 = trim($element['pass2']['#value']); if (!empty($pass1) || !empty($pass2)) { if (strcmp($pass1, $pass2)) { - form_error($element, t('The specified passwords do not match.')); + form_error($element, $element_state, t('The specified passwords do not match.')); } } elseif ($element['#required'] && !empty($element_state['input'])) { - form_error($element, t('Password field is required.')); + form_error($element, $element_state, t('Password field is required.')); } // Password field must be converted from a two-element array into a single @@ -1480,7 +1480,7 @@ function form_validate_pattern($element, &$form_state) { $pattern = '{^(?:' . $element['#pattern'] . ')$}'; if (!preg_match($pattern, $element['#value'])) { - form_error($element, t('%name field is not in the right format.', array('%name' => $element['#title']))); + form_error($element, $form_state, t('%name field is not in the right format.', array('%name' => $element['#title']))); } } } @@ -1790,11 +1790,11 @@ function form_validate_table($element, &$form_state) { } if ($element['#multiple']) { if (!is_array($element['#value']) || !count(array_filter($element['#value']))) { - form_error($element, t('No items selected.')); + form_error($element, $form_state, t('No items selected.')); } } elseif (!isset($element['#value']) || $element['#value'] === '') { - form_error($element, t('No item selected.')); + form_error($element, $form_state, t('No item selected.')); } } @@ -1917,7 +1917,7 @@ function form_process_machine_name($element, &$form_state) { function form_validate_machine_name(&$element, &$form_state) { // Verify that the machine name not only consists of replacement tokens. if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) { - form_error($element, t('The machine-readable name must contain unique characters.')); + form_error($element, $form_state, t('The machine-readable name must contain unique characters.')); } // Verify that the machine name contains no disallowed characters. @@ -1926,15 +1926,15 @@ function form_validate_machine_name(&$element, &$form_state) { // Since a hyphen is the most common alternative replacement character, // a corresponding validation error message is supported here. if ($element['#machine_name']['replace'] == '-') { - form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.')); + form_error($element, $form_state, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.')); } // Otherwise, we assume the default (underscore). else { - form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.')); + form_error($element, $form_state, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.')); } } else { - form_error($element, $element['#machine_name']['error']); + form_error($element, $form_state, $element['#machine_name']['error']); } } @@ -1942,7 +1942,7 @@ function form_validate_machine_name(&$element, &$form_state) { if ($element['#default_value'] !== $element['#value']) { $function = $element['#machine_name']['exists']; if (call_user_func($function, $element['#value'], $element, $form_state)) { - form_error($element, t('The machine-readable name is already in use. It must be unique.')); + form_error($element, $form_state, t('The machine-readable name is already in use. It must be unique.')); } } } @@ -2362,7 +2362,7 @@ function form_validate_email(&$element, &$form_state) { form_set_value($element, $value, $form_state); if ($value !== '' && !valid_email_address($value)) { - form_error($element, t('The e-mail address %mail is not valid.', array('%mail' => $value))); + form_error($element, $form_state, t('The e-mail address %mail is not valid.', array('%mail' => $value))); } } @@ -2438,18 +2438,18 @@ function form_validate_number(&$element, &$form_state) { // Ensure the input is numeric. if (!is_numeric($value)) { - form_error($element, t('%name must be a number.', array('%name' => $name))); + form_error($element, $form_state, t('%name must be a number.', array('%name' => $name))); return; } // Ensure that the input is greater than the #min property, if set. if (isset($element['#min']) && $value < $element['#min']) { - form_error($element, t('%name must be higher than or equal to %min.', array('%name' => $name, '%min' => $element['#min']))); + form_error($element, $form_state, t('%name must be higher than or equal to %min.', array('%name' => $name, '%min' => $element['#min']))); } // Ensure that the input is less than the #max property, if set. if (isset($element['#max']) && $value > $element['#max']) { - form_error($element, t('%name must be lower than or equal to %max.', array('%name' => $name, '%max' => $element['#max']))); + form_error($element, $form_state, t('%name must be lower than or equal to %max.', array('%name' => $name, '%max' => $element['#max']))); } if (isset($element['#step']) && strtolower($element['#step']) != 'any') { @@ -2458,7 +2458,7 @@ function form_validate_number(&$element, &$form_state) { $offset = isset($element['#min']) ? $element['#min'] : 0.0; if (!Number::validStep($value, $element['#step'], $offset)) { - form_error($element, t('%name is not a valid number.', array('%name' => $name))); + form_error($element, $form_state, t('%name is not a valid number.', array('%name' => $name))); } } } @@ -2541,7 +2541,7 @@ function form_validate_url(&$element, &$form_state) { form_set_value($element, $value, $form_state); if ($value !== '' && !valid_url($value, TRUE)) { - form_error($element, t('The URL %url is not valid.', array('%url' => $value))); + form_error($element, $form_state, t('The URL %url is not valid.', array('%url' => $value))); } } @@ -2562,7 +2562,7 @@ function form_validate_color(&$element, &$form_state) { form_set_value($element, Color::rgbToHex(Color::hexToRgb($value)), $form_state); } catch (InvalidArgumentException $e) { - form_error($element, t('%name must be a valid color.', array('%name' => empty($element['#title']) ? $element['#parents'][0] : $element['#title']))); + form_error($element, $form_state, t('%name must be a valid color.', array('%name' => empty($element['#title']) ? $element['#parents'][0] : $element['#title']))); } } } @@ -2931,7 +2931,7 @@ function _form_set_attributes(&$element, $class = array()) { $element['#attributes']['required'] = 'required'; $element['#attributes']['aria-required'] = 'true'; } - if (isset($element['#parents']) && form_get_error($element) !== NULL && !empty($element['#validated'])) { + if (isset($element['#parents']) && isset($element['#errors']) && !empty($element['#validated'])) { $element['#attributes']['class'][] = 'error'; $element['#attributes']['aria-invalid'] = 'true'; } diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc index 36b6b14..7492be7 100644 --- a/core/includes/install.core.inc +++ b/core/includes/install.core.inc @@ -653,7 +653,7 @@ function install_run_task($task, &$install_state) { 'build_info' => array('args' => array(&$install_state)), ); drupal_form_submit($function, $form_state); - $errors = form_get_errors(); + $errors = form_get_errors($form_state); if (!empty($errors)) { throw new Exception(implode("\n", $errors)); } @@ -1194,7 +1194,7 @@ function install_settings_form_validate($form, &$form_state) { $form_state['storage']['database'] = $database; $errors = install_database_errors($database, $form_state['values']['settings_file']); foreach ($errors as $name => $message) { - form_set_error($name, $message); + form_set_error($name, $form_state, $message); } } @@ -2701,7 +2701,7 @@ function _install_configure_form($form, &$form_state, &$install_state) { */ function install_configure_form_validate($form, &$form_state) { if ($error = user_validate_name($form_state['values']['account']['name'])) { - form_error($form['admin_account']['account']['name'], $error); + form_error($form['admin_account']['account']['name'], $form_state, $error); } } diff --git a/core/lib/Drupal/Core/Field/WidgetBase.php b/core/lib/Drupal/Core/Field/WidgetBase.php index 612e668..b371008 100644 --- a/core/lib/Drupal/Core/Field/WidgetBase.php +++ b/core/lib/Drupal/Core/Field/WidgetBase.php @@ -359,7 +359,7 @@ public function flagErrors(FieldItemListInterface $items, array $form, array &$f // @todo: Pass $violation->arrayPropertyPath as property path. $error_element = $this->errorElement($delta_element, $violation, $form, $form_state); if ($error_element !== FALSE) { - form_error($error_element, $violation->getMessage()); + form_error($error_element, $form_state, $violation->getMessage()); } } } diff --git a/core/lib/Drupal/Core/Form/FormBuilder.php b/core/lib/Drupal/Core/Form/FormBuilder.php index cbaf908..974d309 100644 --- a/core/lib/Drupal/Core/Form/FormBuilder.php +++ b/core/lib/Drupal/Core/Form/FormBuilder.php @@ -104,20 +104,6 @@ class FormBuilder implements FormBuilderInterface { protected $forms; /** - * An array of form errors. - * - * @var array - */ - protected $errors = array(); - - /** - * @todo. - * - * @var array - */ - protected $errorSections; - - /** * An array of validated forms. * * @var array @@ -310,6 +296,8 @@ public function getFormStateDefaults() { 'method' => 'post', 'groups' => array(), 'buttons' => array(), + 'errors' => array(), + 'limit_validation_errors' => NULL, ); } @@ -434,6 +422,8 @@ protected function getUncacheableKeys() { 'executed', 'validate_handlers', 'values', + 'errors', + 'limit_validation_errors', ); } @@ -465,7 +455,7 @@ public function submitForm($form_arg, &$form_state) { // Reset form validation. $form_state['must_validate'] = TRUE; - $this->clearErrors(); + $this->clearErrors($form_state); $this->prepareForm($form_id, $form, $form_state); $this->processForm($form_id, $form, $form_state); @@ -616,12 +606,12 @@ public function processForm($form_id, &$form, &$form_state) { // form is processed, so scenarios that result in the form being built // behind the scenes and again for the browser don't increment all the // element IDs needlessly. - if (!$this->getErrors()) { + if (!$this->getAnyErrors()) { // In case of errors, do not break HTML IDs of other forms. $this->drupalStaticReset('drupal_html_id'); } - if ($form_state['submitted'] && !$this->getErrors() && !$form_state['rebuild']) { + if ($form_state['submitted'] && !$this->getAnyErrors() && !$form_state['rebuild']) { // Execute form submit handlers. $this->executeHandlers('submit', $form, $form_state); @@ -686,7 +676,7 @@ public function processForm($form_id, &$form, &$form_state) { // along with element-level #submit properties, it makes no sense to // have divergent form execution based on whether the triggering element // has #executes_submit_callback set to TRUE. - if (($form_state['rebuild'] || !$form_state['executed']) && !$this->getErrors()) { + if (($form_state['rebuild'] || !$form_state['executed']) && !$this->getAnyErrors()) { // Form building functions (e.g., self::handleInputElement()) may use // $form_state['rebuild'] to determine if they are running in the // context of a rebuild, so ensure it is set. @@ -860,11 +850,15 @@ public function validateForm($form_id, &$form, &$form_state) { $url = $this->urlGenerator->generateFromPath($path, array('query' => $query)); // Setting this error will cause the form to fail validation. - $this->setErrorByName('form_token', $this->t('The form has become outdated. Copy any unsaved work in the form below and then reload this page.', array('@link' => $url))); + $this->setErrorByName('form_token', $form_state, $this->t('The form has become outdated. Copy any unsaved work in the form below and then reload this page.', array('@link' => $url))); } } + // Recursively validate each form element. $this->doValidateForm($form, $form_state, $form_id); + // After validation, loop through and assign each element its errors. + $this->setElementErrorsFromFormState($form, $form_state); + // Mark this form as validated. $this->validatedForms[$form_id] = TRUE; // If validation errors are limited then remove any non validated form values, @@ -1018,7 +1012,7 @@ protected function doValidateForm(&$elements, &$form_state, $form_id = NULL) { if (isset($elements['#needs_validation'])) { // Verify that the value is not longer than #maxlength. if (isset($elements['#maxlength']) && Unicode::strlen($elements['#value']) > $elements['#maxlength']) { - $this->setError($elements, $this->t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => Unicode::strlen($elements['#value'])))); + $this->setError($elements, $form_state, $this->t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => Unicode::strlen($elements['#value'])))); } if (isset($elements['#options']) && isset($elements['#value'])) { @@ -1032,7 +1026,7 @@ protected function doValidateForm(&$elements, &$form_state, $form_id = NULL) { $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value']; foreach ($value as $v) { if (!isset($options[$v])) { - $this->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.')); + $this->setError($elements, $form_state, $this->t('An illegal choice has been detected. Please contact the site administrator.')); $this->watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR); } } @@ -1051,7 +1045,7 @@ protected function doValidateForm(&$elements, &$form_state, $form_id = NULL) { $this->setValue($elements, NULL, $form_state); } elseif (!isset($options[$elements['#value']])) { - $this->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.')); + $this->setError($elements, $form_state, $this->t('An illegal choice has been detected. Please contact the site administrator.')); $this->watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR); } } @@ -1069,7 +1063,7 @@ protected function doValidateForm(&$elements, &$form_state, $form_id = NULL) { // too large a security risk to have any invalid user input when executing // form-level submit handlers. if (isset($form_state['triggering_element']['#limit_validation_errors']) && ($form_state['triggering_element']['#limit_validation_errors'] !== FALSE) && !($form_state['submitted'] && !isset($form_state['triggering_element']['#submit']))) { - $this->setErrorByName(NULL, '', $form_state['triggering_element']['#limit_validation_errors']); + $form_state['limit_validation_errors'] = $form_state['triggering_element']['#limit_validation_errors']; } // If submit handlers won't run (due to the submission having been // triggered by an element whose #executes_submit_callback property isn't @@ -1081,14 +1075,14 @@ protected function doValidateForm(&$elements, &$form_state, $form_id = NULL) { // system_element_info()), so that full validation is their default // behavior. elseif (isset($form_state['triggering_element']) && !isset($form_state['triggering_element']['#limit_validation_errors']) && !$form_state['submitted']) { - $this->setErrorByName(NULL, '', array()); + $form_state['limit_validation_errors'] = array(); } // As an extra security measure, explicitly turn off error suppression if // one of the above conditions wasn't met. Since this is also done at the // end of this function, doing it here is only to handle the rare edge // case where a validate handler invokes form processing of another form. else { - $this->errorSections = NULL; + $form_state['limit_validation_errors'] = NULL; } // Make sure a value is passed when the field is required. @@ -1128,17 +1122,17 @@ protected function doValidateForm(&$elements, &$form_state, $form_id = NULL) { // variables are also known to be defined and we can test them again. if (isset($is_empty_value) && ($is_empty_multiple || $is_empty_string || $is_empty_value)) { if (isset($elements['#required_error'])) { - $this->setError($elements, $elements['#required_error']); + $this->setError($elements, $form_state, $elements['#required_error']); } // A #title is not mandatory for form elements, but without it we cannot // set a form error message. So when a visible title is undesirable, // form constructors are encouraged to set #title anyway, and then set // #title_display to 'invisible'. This improves accessibility. elseif (isset($elements['#title'])) { - $this->setError($elements, $this->t('!name field is required.', array('!name' => $elements['#title']))); + $this->setError($elements, $form_state, $this->t('!name field is required.', array('!name' => $elements['#title']))); } else { - $this->setError($elements); + $this->setError($elements, $form_state); } } @@ -1148,7 +1142,30 @@ protected function doValidateForm(&$elements, &$form_state, $form_id = NULL) { // Done validating this element, so turn off error suppression. // self::doValidateForm() turns it on again when starting on the next // element, if it's still appropriate to do so. - $this->errorSections = NULL; + $form_state['limit_validation_errors'] = NULL; + } + + /** + * Stores the errors of each element directly on the element. + * + * Because self::getError() and self::getErrors() require the $form_state, + * we must provide a way for non-form functions to check the errors for a + * specific element. The most common usage of this is a #pre_render callback. + * + * @param array $elements + * An associative array containing the structure of a form element. + * @param array $form_state + * An associative array containing the current state of the form. + */ + protected function setElementErrorsFromFormState(array &$elements, array &$form_state) { + // Recurse through all children. + foreach ($this->elementChildren($elements) as $key) { + if (isset($elements[$key]) && $elements[$key]) { + $this->setElementErrorsFromFormState($elements[$key], $form_state); + } + } + // Store the errors for this element on the element directly. + $elements['#errors'] = $this->getError($elements, $form_state); } /** @@ -1187,14 +1204,10 @@ public function executeHandlers($type, &$form, &$form_state) { /** * {@inheritdoc} */ - public function setErrorByName($name = NULL, $message = '', $limit_validation_errors = NULL) { - if (isset($limit_validation_errors)) { - $this->errorSections = $limit_validation_errors; - } - - if (isset($name) && !isset($this->errors[$name])) { + public function setErrorByName($name, array &$form_state, $message = '') { + if (!isset($form_state['errors'][$name])) { $record = TRUE; - if (isset($this->errorSections)) { + if (isset($form_state['limit_validation_errors'])) { // #limit_validation_errors is an array of "sections" within which user // input must be valid. If the element is within one of these sections, // the error must be recorded. Otherwise, it can be suppressed. @@ -1203,7 +1216,7 @@ public function setErrorByName($name = NULL, $message = '', $limit_validation_er // its submit action to be triggered even if none of the submitted // values are valid. $record = FALSE; - foreach ($this->errorSections as $section) { + foreach ($form_state['limit_validation_errors'] as $section) { // Exploding by '][' reconstructs the element's #parents. If the // reconstructed #parents begin with the same keys as the specified // section, then the element's values are within the part of @@ -1218,44 +1231,51 @@ public function setErrorByName($name = NULL, $message = '', $limit_validation_er } } if ($record) { - $this->errors[$name] = $message; + $form_state['errors'][$name] = $message; + $this->request->attributes->set('_form_errors', TRUE); if ($message) { $this->drupalSetMessage($message, 'error'); } } } - return $this->errors; + return $form_state['errors']; } /** * {@inheritdoc} */ - public function clearErrors() { - $this->errors = array(); + public function clearErrors(array &$form_state) { + $form_state['errors'] = array(); + $this->request->attributes->set('_form_errors', FALSE); } /** * {@inheritdoc} */ - public function getErrors() { - $form = $this->setErrorByName(); - if (!empty($form)) { - return $form; - } + public function getErrors(array $form_state) { + return $form_state['errors']; } /** * {@inheritdoc} */ - public function getError($element) { - $form = $this->setErrorByName(); - $parents = array(); - foreach ($element['#parents'] as $parent) { - $parents[] = $parent; - $key = implode('][', $parents); - if (isset($form[$key])) { - return $form[$key]; + public function getAnyErrors() { + return (bool) $this->request->attributes->get('_form_errors'); + } + + /** + * {@inheritdoc} + */ + public function getError($element, array &$form_state) { + if ($errors = $this->getErrors($form_state)) { + $parents = array(); + foreach ($element['#parents'] as $parent) { + $parents[] = $parent; + $key = implode('][', $parents); + if (isset($errors[$key])) { + return $errors[$key]; + } } } } @@ -1263,8 +1283,8 @@ public function getError($element) { /** * {@inheritdoc} */ - public function setError(&$element, $message = '') { - $this->setErrorByName(implode('][', $element['#parents']), $message); + public function setError(&$element, array &$form_state, $message = '') { + $this->setErrorByName(implode('][', $element['#parents']), $form_state, $message); } /** @@ -1285,6 +1305,7 @@ public function doBuildForm($form_id, &$element, &$form_state) { '#required' => FALSE, '#attributes' => array(), '#title_display' => 'before', + '#errors' => NULL, ); // Special handling if we're on the top level form element. diff --git a/core/lib/Drupal/Core/Form/FormBuilderInterface.php b/core/lib/Drupal/Core/Form/FormBuilderInterface.php index aa09c41..8a6f22b 100644 --- a/core/lib/Drupal/Core/Form/FormBuilderInterface.php +++ b/core/lib/Drupal/Core/Form/FormBuilderInterface.php @@ -12,7 +12,7 @@ /** * Provides an interface for form building and processing. */ -interface FormBuilderInterface { +interface FormBuilderInterface extends FormErrorInterface { /** * Determines the form ID. @@ -509,128 +509,6 @@ public function redirectForm($form_state); public function executeHandlers($type, &$form, &$form_state); /** - * Files an error against a form element. - * - * When a validation error is detected, the validator calls form_set_error() - * to indicate which element needs to be changed and provide an error message. - * This causes the Form API to not execute the form submit handlers, and - * instead to re-display the form to the user with the corresponding elements - * rendered with an 'error' CSS class (shown as red by default). - * - * The standard form_set_error() behavior can be changed if a button provides - * the #limit_validation_errors property. Multistep forms not wanting to - * validate the whole form can set #limit_validation_errors on buttons to - * limit validation errors to only certain elements. For example, pressing the - * "Previous" button in a multistep form should not fire validation errors - * just because the current step has invalid values. If - * #limit_validation_errors is set on a clicked button, the button must also - * define a #submit property (may be set to an empty array). Any #submit - * handlers will be executed even if there is invalid input, so extreme care - * should be taken with respect to any actions taken by them. This is - * typically not a problem with buttons like "Previous" or "Add more" that do - * not invoke persistent storage of the submitted form values. Do not use the - * #limit_validation_errors property on buttons that trigger saving of form - * values to the database. - * - * The #limit_validation_errors property is a list of "sections" within - * $form_state['values'] that must contain valid values. Each "section" is an - * array with the ordered set of keys needed to reach that part of - * $form_state['values'] (i.e., the #parents property of the element). - * - * Example 1: Allow the "Previous" button to function, regardless of whether - * any user input is valid. - * - * @code - * $form['actions']['previous'] = array( - * '#type' => 'submit', - * '#value' => t('Previous'), - * '#limit_validation_errors' => array(), // No validation. - * '#submit' => array('some_submit_function'), // #submit required. - * ); - * @endcode - * - * Example 2: Require some, but not all, user input to be valid to process the - * submission of a "Previous" button. - * - * @code - * $form['actions']['previous'] = array( - * '#type' => 'submit', - * '#value' => t('Previous'), - * '#limit_validation_errors' => array( - * array('step1'), // Validate $form_state['values']['step1']. - * array('foo', 'bar'), // Validate $form_state['values']['foo']['bar']. - * ), - * '#submit' => array('some_submit_function'), // #submit required. - * ); - * @endcode - * - * This will require $form_state['values']['step1'] and everything within it - * (for example, $form_state['values']['step1']['choice']) to be valid, so - * calls to form_set_error('step1', $message) or - * form_set_error('step1][choice', $message) will prevent the submit handlers - * from running, and result in the error message being displayed to the user. - * However, calls to form_set_error('step2', $message) and - * form_set_error('step2][groupX][choiceY', $message) will be suppressed, - * resulting in the message not being displayed to the user, and the submit - * handlers will run despite $form_state['values']['step2'] and - * $form_state['values']['step2']['groupX']['choiceY'] containing invalid - * values. Errors for an invalid $form_state['values']['foo'] will be - * suppressed, but errors flagging invalid values for - * $form_state['values']['foo']['bar'] and everything within it will be - * flagged and submission prevented. - * - * Partial form validation is implemented by suppressing errors rather than by - * skipping the input processing and validation steps entirely, because some - * forms have button-level submit handlers that call Drupal API functions that - * assume that certain data exists within $form_state['values'], and while not - * doing anything with that data that requires it to be valid, PHP errors - * would be triggered if the input processing and validation steps were fully - * skipped. - * - * @param $name - * The name of the form element. If the #parents property of your form - * element is array('foo', 'bar', 'baz') then you may set an error on 'foo' - * or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every - * element where the #parents array starts with 'foo'. - * @param $message - * The error message to present to the user. - * @param $limit_validation_errors - * Internal use only. The #limit_validation_errors property of the clicked - * button, if it exists. - * - * @return mixed - * Return value is for internal use only. To get a list of errors, use - * form_get_errors() or form_get_error(). - * - * @see http://drupal.org/node/370537 - * @see http://drupal.org/node/763376 - */ - public function setErrorByName($name = NULL, $message = '', $limit_validation_errors = NULL); - - /** - * Clears all errors against all form elements made by form_set_error(). - */ - public function clearErrors(); - - /** - * Returns an associative array of all errors. - */ - public function getErrors(); - - /** - * Returns the error message filed against the given form element. - * - * Form errors higher up in the form structure override deeper errors as well - * as errors on the element itself. - */ - public function getError($element); - - /** - * Flags an element as having an error. - */ - public function setError(&$element, $message = ''); - - /** * Builds and processes all elements in the structured form array. * * Adds any required properties to each element, maps the incoming input data diff --git a/core/lib/Drupal/Core/Form/FormErrorInterface.php b/core/lib/Drupal/Core/Form/FormErrorInterface.php new file mode 100644 index 0000000..c642ed3 --- /dev/null +++ b/core/lib/Drupal/Core/Form/FormErrorInterface.php @@ -0,0 +1,164 @@ + 'submit', + * '#value' => t('Previous'), + * '#limit_validation_errors' => array(), // No validation. + * '#submit' => array('some_submit_function'), // #submit required. + * ); + * @endcode + * + * Example 2: Require some, but not all, user input to be valid to process the + * submission of a "Previous" button. + * + * @code + * $form['actions']['previous'] = array( + * '#type' => 'submit', + * '#value' => t('Previous'), + * '#limit_validation_errors' => array( + * array('step1'), // Validate $form_state['values']['step1']. + * array('foo', 'bar'), // Validate $form_state['values']['foo']['bar']. + * ), + * '#submit' => array('some_submit_function'), // #submit required. + * ); + * @endcode + * + * This will require $form_state['values']['step1'] and everything within it + * (for example, $form_state['values']['step1']['choice']) to be valid, so + * calls to form_set_error('step1', $form_state, $message) or + * form_set_error('step1][choice', $form_state, $message) will prevent the + * submit handlers from running, and result in the error message being + * displayed to the user. However, calls to + * form_set_error('step2', $form_state, $message) and + * form_set_error('step2][groupX][choiceY', $form_state, $message) will be + * suppressed, resulting in the message not being displayed to the user, and + * the submitdoCheckErrors handlers will run despite $form_state['values']['step2'] and + * $form_state['values']['step2']['groupX']['choiceY'] containing invalid + * values. Errors for an invalid $form_state['values']['foo'] will be + * suppressed, but errors flagging invalid values for + * $form_state['values']['foo']['bar'] and everything within it will be + * flagged and submission prevented. + * + * Partial form validation is implemented by suppressing errors rather than by + * skipping the input processing and validation steps entirely, because some + * forms have button-level submit handlers that call Drupal API functions that + * assume that certain data exists within $form_state['values'], and while not + * doing anything with that data that requires it to be valid, PHP errors + * would be triggered if the input processing and validation steps were fully + * skipped. + * + * @param $name + * The name of the form element. If the #parents property of your form + * element is array('foo', 'bar', 'baz') then you may set an error on 'foo' + * or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every + * element where the #parents array starts with 'foo'. + * @param array $form_state + * An associative array containing the current state of the form. + * @param $message + * The error message to present to the user. + * + * @return mixed + * Return value is for internal use only. To get a list of errors, use + * form_get_errors() or form_get_error(). + * + * @see http://drupal.org/node/370537 + * @see http://drupal.org/node/763376 + */ + public function setErrorByName($name, array &$form_state, $message = ''); + + /** + * Clears all errors against all form elements made by form_set_error(). + * + * @param array $form_state + * An associative array containing the current state of the form. + */ + public function clearErrors(array &$form_state); + + /** + * Returns an associative array of all errors. + * + * @param array $form_state + * An associative array containing the current state of the form. + * + * @return array + * An array of all errors, keyed by the name of the form element. + */ + public function getErrors(array $form_state); + + /** + * Returns the error message filed against the given form element. + * + * Form errors higher up in the form structure override deeper errors as well + * as errors on the element itself. + * + * @param array $element + * The form element to check for errors. + * @param array $form_state + * An associative array containing the current state of the form. + * + * @return string|null + * Either the error message for this element or NULL if there are no errors. + */ + public function getError($element, array &$form_state); + + /** + * Flags an element as having an error. + */ + public function setError(&$element, array &$form_state, $message = ''); + + /** + * Returns if there have been any errors during build. + * + * This will include any forms built during this request. + * + * @return bool + * Whether there have been any errors. + */ + public function getAnyErrors(); + +} diff --git a/core/modules/action/lib/Drupal/action/Plugin/Action/EmailAction.php b/core/modules/action/lib/Drupal/action/Plugin/Action/EmailAction.php index 3275a4a..fef70fd 100644 --- a/core/modules/action/lib/Drupal/action/Plugin/Action/EmailAction.php +++ b/core/modules/action/lib/Drupal/action/Plugin/Action/EmailAction.php @@ -148,7 +148,7 @@ public function buildConfigurationForm(array $form, array &$form_state) { public function validateConfigurationForm(array &$form, array &$form_state) { if (!valid_email_address($form_state['values']['recipient']) && strpos($form_state['values']['recipient'], ':mail') === FALSE) { // We want the literal %author placeholder to be emphasized in the error message. - form_set_error('recipient', t('Enter a valid email address or use a token e-mail address such as %author.', array('%author' => '[node:author:mail]'))); + form_set_error('recipient', $form_state, t('Enter a valid email address or use a token e-mail address such as %author.', array('%author' => '[node:author:mail]'))); } } diff --git a/core/modules/aggregator/lib/Drupal/aggregator/FeedFormController.php b/core/modules/aggregator/lib/Drupal/aggregator/FeedFormController.php index 899bb40..78aa4e3 100644 --- a/core/modules/aggregator/lib/Drupal/aggregator/FeedFormController.php +++ b/core/modules/aggregator/lib/Drupal/aggregator/FeedFormController.php @@ -122,10 +122,10 @@ public function validate(array $form, array &$form_state) { $result = $feed_storage_controller->getFeedDuplicates($feed); foreach ($result as $item) { if (strcasecmp($item->title, $feed->label()) == 0) { - form_set_error('title', $this->t('A feed named %feed already exists. Enter a unique title.', array('%feed' => $feed->label()))); + form_set_error('title', $form_state, $this->t('A feed named %feed already exists. Enter a unique title.', array('%feed' => $feed->label()))); } if (strcasecmp($item->url, $feed->url->value) == 0) { - form_set_error('url', $this->t('A feed with this URL %url already exists. Enter a unique URL.', array('%url' => $feed->url->value))); + form_set_error('url', $form_state, $this->t('A feed with this URL %url already exists. Enter a unique URL.', array('%url' => $feed->url->value))); } } parent::validate($form, $form_state); diff --git a/core/modules/aggregator/lib/Drupal/aggregator/Form/CategoryAdminForm.php b/core/modules/aggregator/lib/Drupal/aggregator/Form/CategoryAdminForm.php index a24a420..4d5eeee 100644 --- a/core/modules/aggregator/lib/Drupal/aggregator/Form/CategoryAdminForm.php +++ b/core/modules/aggregator/lib/Drupal/aggregator/Form/CategoryAdminForm.php @@ -125,7 +125,7 @@ public function validateForm(array &$form, array &$form_state) { $unique = $this->categoryStorageController->isUnique($title); } if (!$unique) { - form_set_error('title', $this->t('A category named %category already exists. Enter a unique title.', array('%category' => $title))); + form_set_error('title', $form_state, $this->t('A category named %category already exists. Enter a unique title.', array('%category' => $title))); } } } diff --git a/core/modules/aggregator/lib/Drupal/aggregator/Form/OpmlFeedAdd.php b/core/modules/aggregator/lib/Drupal/aggregator/Form/OpmlFeedAdd.php index 748574f..3a4a131 100644 --- a/core/modules/aggregator/lib/Drupal/aggregator/Form/OpmlFeedAdd.php +++ b/core/modules/aggregator/lib/Drupal/aggregator/Form/OpmlFeedAdd.php @@ -139,7 +139,7 @@ public function buildForm(array $form, array &$form_state) { public function validateForm(array &$form, array &$form_state) { // If both fields are empty or filled, cancel. if (empty($form_state['values']['remote']) == empty($_FILES['files']['name']['upload'])) { - form_set_error('remote', $this->t('You must either upload a file or enter a URL.')); + form_set_error('remote', $form_state, $this->t('You must either upload a file or enter a URL.')); } } @@ -148,7 +148,7 @@ public function validateForm(array &$form, array &$form_state) { */ public function submitForm(array &$form, array &$form_state) { $validators = array('file_validate_extensions' => array('opml xml')); - if ($file = file_save_upload('upload', $validators, FALSE, 0)) { + if ($file = file_save_upload('upload', $form_state, $validators, FALSE, 0)) { $data = file_get_contents($file->getFileUri()); } else { diff --git a/core/modules/ban/lib/Drupal/ban/Form/BanAdmin.php b/core/modules/ban/lib/Drupal/ban/Form/BanAdmin.php index 572584a..f03d292 100644 --- a/core/modules/ban/lib/Drupal/ban/Form/BanAdmin.php +++ b/core/modules/ban/lib/Drupal/ban/Form/BanAdmin.php @@ -105,13 +105,13 @@ public function buildForm(array $form, array &$form_state, $default_ip = '') { public function validateForm(array &$form, array &$form_state) { $ip = trim($form_state['values']['ip']); if ($this->ipManager->isBanned($ip)) { - form_set_error('ip', $this->t('This IP address is already banned.')); + form_set_error('ip', $form_state, $this->t('This IP address is already banned.')); } elseif ($ip == $this->getRequest()->getClientIP()) { - form_set_error('ip', $this->t('You may not ban your own IP address.')); + form_set_error('ip', $form_state, $this->t('You may not ban your own IP address.')); } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) { - form_set_error('ip', $this->t('Enter a valid IP address.')); + form_set_error('ip', $form_state, $this->t('Enter a valid IP address.')); } } diff --git a/core/modules/block/custom_block/lib/Drupal/custom_block/CustomBlockFormController.php b/core/modules/block/custom_block/lib/Drupal/custom_block/CustomBlockFormController.php index ffa7d47..edae0ca 100644 --- a/core/modules/block/custom_block/lib/Drupal/custom_block/CustomBlockFormController.php +++ b/core/modules/block/custom_block/lib/Drupal/custom_block/CustomBlockFormController.php @@ -238,7 +238,7 @@ public function validateForm(array &$form, array &$form_state) { // @todo Inject this once https://drupal.org/node/2060865 is in. $exists = \Drupal::entityManager()->getStorageController('custom_block')->loadByProperties(array('info' => $form_state['values']['info'])); if (!empty($exists)) { - form_set_error('info', t('A block with description %name already exists.', array( + form_set_error('info', $form_state, t('A block with description %name already exists.', array( '%name' => $form_state['values']['info'] ))); } diff --git a/core/modules/block/lib/Drupal/block/BlockBase.php b/core/modules/block/lib/Drupal/block/BlockBase.php index 23828e6..62afa32 100644 --- a/core/modules/block/lib/Drupal/block/BlockBase.php +++ b/core/modules/block/lib/Drupal/block/BlockBase.php @@ -148,7 +148,7 @@ public function blockValidate($form, &$form_state) {} */ public function submitConfigurationForm(array &$form, array &$form_state) { // Process the block's submission handling if no errors occurred only. - if (!form_get_errors()) { + if (!form_get_errors($form_state)) { $this->configuration['label'] = $form_state['values']['label']; $this->configuration['label_display'] = $form_state['values']['label_display']; $this->configuration['module'] = $form_state['values']['module']; diff --git a/core/modules/block/lib/Drupal/block/BlockFormController.php b/core/modules/block/lib/Drupal/block/BlockFormController.php index 6d88f11..5965c21 100644 --- a/core/modules/block/lib/Drupal/block/BlockFormController.php +++ b/core/modules/block/lib/Drupal/block/BlockFormController.php @@ -313,8 +313,10 @@ public function submit(array $form, array &$form_state) { $entity = $this->entity; // The Block Entity form puts all block plugin form elements in the // settings form element, so just pass that to the block for submission. + // @todo Find a way to avoid this manipulation. $settings = array( - 'values' => &$form_state['values']['settings'] + 'values' => &$form_state['values']['settings'], + 'errors' => $form_state['errors'], ); // Call the plugin submit handler. $entity->getPlugin()->submitConfigurationForm($form, $settings); diff --git a/core/modules/book/lib/Drupal/book/Form/BookAdminEditForm.php b/core/modules/book/lib/Drupal/book/Form/BookAdminEditForm.php index 0c0d7b5..ddf49b0 100644 --- a/core/modules/book/lib/Drupal/book/Form/BookAdminEditForm.php +++ b/core/modules/book/lib/Drupal/book/Form/BookAdminEditForm.php @@ -96,7 +96,7 @@ public function buildForm(array $form, array &$form_state, NodeInterface $node = */ public function validateForm(array &$form, array &$form_state) { if ($form_state['values']['tree_hash'] != $form_state['values']['tree_current_hash']) { - form_set_error('', $this->t('This book has been modified by another user, the changes could not be saved.')); + form_set_error('', $form_state, $this->t('This book has been modified by another user, the changes could not be saved.')); } } diff --git a/core/modules/book/lib/Drupal/book/Form/BookSettingsForm.php b/core/modules/book/lib/Drupal/book/Form/BookSettingsForm.php index d5a8c84..1bc25a7 100644 --- a/core/modules/book/lib/Drupal/book/Form/BookSettingsForm.php +++ b/core/modules/book/lib/Drupal/book/Form/BookSettingsForm.php @@ -53,7 +53,7 @@ public function buildForm(array $form, array &$form_state) { public function validateForm(array &$form, array &$form_state) { $child_type = $form_state['values']['book_child_type']; if (empty($form_state['values']['book_allowed_types'][$child_type])) { - form_set_error('book_child_type', $this->t('The content type for the %add-child link must be one of those selected as an allowed book outline type.', array('%add-child' => $this->t('Add child page')))); + form_set_error('book_child_type', $form_state, $this->t('The content type for the %add-child link must be one of those selected as an allowed book outline type.', array('%add-child' => $this->t('Add child page')))); } parent::validateForm($form, $form_state); diff --git a/core/modules/ckeditor/lib/Drupal/ckeditor/Plugin/CKEditorPlugin/StylesCombo.php b/core/modules/ckeditor/lib/Drupal/ckeditor/Plugin/CKEditorPlugin/StylesCombo.php index 3adb74f..47b88c2 100644 --- a/core/modules/ckeditor/lib/Drupal/ckeditor/Plugin/CKEditorPlugin/StylesCombo.php +++ b/core/modules/ckeditor/lib/Drupal/ckeditor/Plugin/CKEditorPlugin/StylesCombo.php @@ -96,7 +96,7 @@ public function settingsForm(array $form, array &$form_state, Editor $editor) { */ public function validateStylesValue(array $element, array &$form_state) { if ($this->generateStylesSetSetting($element['#value']) === FALSE) { - form_error($element, t('The provided list of styles is syntactically incorrect.')); + form_error($element, $form_state, t('The provided list of styles is syntactically incorrect.')); } } diff --git a/core/modules/color/color.module b/core/modules/color/color.module index e9710c2..c4079b1 100644 --- a/core/modules/color/color.module +++ b/core/modules/color/color.module @@ -263,7 +263,7 @@ function color_scheme_form_validate($form, &$form_state) { // Only accept hexadecimal CSS color strings to avoid XSS upon use. foreach ($form_state['values']['palette'] as $key => $color) { if (!preg_match('/^#([a-f0-9]{3}){1,2}$/iD', $color)) { - form_set_error('palette][' . $key, t('You must enter a valid hexadecimal color value for %name.', array('%name' => $form['color']['palette'][$key]['#title']))); + form_set_error('palette][' . $key, $form_state, t('You must enter a valid hexadecimal color value for %name.', array('%name' => $form['color']['palette'][$key]['#title']))); } } } diff --git a/core/modules/comment/comment.admin.inc b/core/modules/comment/comment.admin.inc index 2013de8..7132ae2 100644 --- a/core/modules/comment/comment.admin.inc +++ b/core/modules/comment/comment.admin.inc @@ -194,7 +194,7 @@ function comment_admin_overview_validate($form, &$form_state) { $form_state['values']['comments'] = array_diff($form_state['values']['comments'], array(0)); // We can't execute any 'Update options' if no comments were selected. if (count($form_state['values']['comments']) == 0) { - form_set_error('', t('Select one or more comments to perform the update on.')); + form_set_error('', $form_state, t('Select one or more comments to perform the update on.')); } } diff --git a/core/modules/comment/comment.module b/core/modules/comment/comment.module index 9f8b282..6fcbc2b 100644 --- a/core/modules/comment/comment.module +++ b/core/modules/comment/comment.module @@ -1285,12 +1285,12 @@ function comment_get_display_page($cid, $instance) { * * @param \Drupal\comment\CommentInterface $comment */ -function comment_preview(CommentInterface $comment) { +function comment_preview(CommentInterface $comment, array &$form_state) { global $user; $preview_build = array(); $entity = entity_load($comment->entity_type->value, $comment->entity_id->value); - if (!form_get_errors()) { + if (!form_get_errors($form_state)) { // Attach the user and time information. if (!empty($comment->name->value)) { $account = user_load_by_name($comment->name->value); diff --git a/core/modules/comment/lib/Drupal/comment/CommentFormController.php b/core/modules/comment/lib/Drupal/comment/CommentFormController.php index f0c38ad..d50605d 100644 --- a/core/modules/comment/lib/Drupal/comment/CommentFormController.php +++ b/core/modules/comment/lib/Drupal/comment/CommentFormController.php @@ -275,10 +275,10 @@ public function validate(array $form, array &$form_state) { $date = $form_state['values']['date']; if ($date instanceOf DrupalDateTime && $date->hasErrors()) { - form_set_error('date', $this->t('You have to specify a valid date.')); + form_set_error('date', $form_state, $this->t('You have to specify a valid date.')); } if ($form_state['values']['name'] && !$form_state['values']['is_anonymous'] && !$account) { - form_set_error('name', $this->t('You have to specify a valid author.')); + form_set_error('name', $form_state, $this->t('You have to specify a valid author.')); } } elseif ($form_state['values']['is_anonymous']) { @@ -288,7 +288,7 @@ public function validate(array $form, array &$form_state) { if ($form_state['values']['name']) { $accounts = $this->entityManager->getStorageController('user')->loadByProperties(array('name' => $form_state['values']['name'])); if (!empty($accounts)) { - form_set_error('name', $this->t('The name you used belongs to a registered user.')); + form_set_error('name', $form_state, $this->t('The name you used belongs to a registered user.')); } } } @@ -356,7 +356,7 @@ public function submit(array $form, array &$form_state) { */ public function preview(array $form, array &$form_state) { $comment = $this->entity; - $form_state['comment_preview'] = comment_preview($comment); + $form_state['comment_preview'] = comment_preview($comment, $form_state); $form_state['comment_preview']['#title'] = $this->t('Preview comment'); $form_state['rebuild'] = TRUE; } diff --git a/core/modules/config/lib/Drupal/config/Form/ConfigImportForm.php b/core/modules/config/lib/Drupal/config/Form/ConfigImportForm.php index c6a9304..be2988e 100644 --- a/core/modules/config/lib/Drupal/config/Form/ConfigImportForm.php +++ b/core/modules/config/lib/Drupal/config/Form/ConfigImportForm.php @@ -75,7 +75,7 @@ public function buildForm(array $form, array &$form_state) { */ public function validateForm(array &$form, array &$form_state) { if (!empty($_FILES['files']['error']['import_tarball'])) { - form_set_error('import_tarball', $this->t('The import tarball could not be uploaded.')); + form_set_error('import_tarball', $form_state, $this->t('The import tarball could not be uploaded.')); } else { $form_state['values']['import_tarball'] = $_FILES['files']['tmp_name']['import_tarball']; @@ -99,7 +99,7 @@ public function submitForm(array &$form, array &$form_state) { $form_state['redirect_route']['route_name'] = 'config.sync'; } catch (\Exception $e) { - form_set_error('import_tarball', $this->t('Could not extract the contents of the tar file. The error message is @message', array('@message' => $e->getMessage()))); + form_set_error('import_tarball', $form_state, $this->t('Could not extract the contents of the tar file. The error message is @message', array('@message' => $e->getMessage()))); } drupal_unlink($path); } diff --git a/core/modules/config/lib/Drupal/config/Form/ConfigSingleImportForm.php b/core/modules/config/lib/Drupal/config/Form/ConfigSingleImportForm.php index 5b14554..24913c7 100644 --- a/core/modules/config/lib/Drupal/config/Form/ConfigSingleImportForm.php +++ b/core/modules/config/lib/Drupal/config/Form/ConfigSingleImportForm.php @@ -183,7 +183,7 @@ public function validateForm(array &$form, array &$form_state) { $entity_storage = $this->entityManager->getStorageController($form_state['values']['config_type']); // If an entity ID was not specified, set an error. if (!isset($data[$id_key])) { - form_set_error('import', $this->t('Missing ID key "@id_key" for this @entity_type import.', array('@id_key' => $id_key, '@entity_type' => $definition['label']))); + form_set_error('import', $form_state, $this->t('Missing ID key "@id_key" for this @entity_type import.', array('@id_key' => $id_key, '@entity_type' => $definition['label']))); return; } $uuid_key = $definition['entity_keys']['uuid']; @@ -191,17 +191,17 @@ public function validateForm(array &$form, array &$form_state) { if ($entity = $entity_storage->load($data[$id_key])) { $this->configExists = $entity; if (!isset($data[$uuid_key])) { - form_set_error('import', $this->t('An entity with this machine name already exists but the import did not specify a UUID.')); + form_set_error('import', $form_state, $this->t('An entity with this machine name already exists but the import did not specify a UUID.')); return; } if ($data[$uuid_key] !== $entity->uuid()) { - form_set_error('import', $this->t('An entity with this machine name already exists but the UUID does not match.')); + form_set_error('import', $form_state, $this->t('An entity with this machine name already exists but the UUID does not match.')); return; } } // If there is no entity with a matching ID, check for a UUID match. elseif (isset($data[$uuid_key]) && $entity_storage->loadByProperties(array($uuid_key => $data[$uuid_key]))) { - form_set_error('import', $this->t('An entity with this UUID already exists but the machine name does not match.')); + form_set_error('import', $form_state, $this->t('An entity with this UUID already exists but the machine name does not match.')); } } else { diff --git a/core/modules/contact/lib/Drupal/contact/CategoryFormController.php b/core/modules/contact/lib/Drupal/contact/CategoryFormController.php index a383881..d1eb9b4 100644 --- a/core/modules/contact/lib/Drupal/contact/CategoryFormController.php +++ b/core/modules/contact/lib/Drupal/contact/CategoryFormController.php @@ -84,7 +84,7 @@ public function validate(array $form, array &$form_state) { foreach ($recipients as &$recipient) { $recipient = trim($recipient); if (!valid_email_address($recipient)) { - form_set_error('recipients', t('%recipient is an invalid e-mail address.', array('%recipient' => $recipient))); + form_set_error('recipients', $form_state, t('%recipient is an invalid e-mail address.', array('%recipient' => $recipient))); } } $form_state['values']['recipients'] = $recipients; diff --git a/core/modules/content_translation/content_translation.admin.inc b/core/modules/content_translation/content_translation.admin.inc index 6d02b9d..f621b2f 100644 --- a/core/modules/content_translation/content_translation.admin.inc +++ b/core/modules/content_translation/content_translation.admin.inc @@ -271,7 +271,7 @@ function content_translation_form_language_content_settings_validate(array $form $translatable_fields = isset($settings[$entity_type][$bundle]['fields']) ? array_filter($settings[$entity_type][$bundle]['fields']) : FALSE; if (empty($translatable_fields)) { $t_args = array('%bundle' => $form['settings'][$entity_type][$bundle]['settings']['#label']); - form_set_error($name, t('At least one field needs to be translatable to enable %bundle for translation.', $t_args)); + form_set_error($name, $form_state, t('At least one field needs to be translatable to enable %bundle for translation.', $t_args)); } $values = $bundle_settings['settings']['language']; @@ -279,7 +279,7 @@ function content_translation_form_language_content_settings_validate(array $form foreach (language_list(Language::STATE_LOCKED) as $language) { $locked_languages[] = $language->name; } - form_set_error($name, t('Translation is not supported if language is always one of: @locked_languages', array('@locked_languages' => implode(', ', $locked_languages)))); + form_set_error($name, $form_state, t('Translation is not supported if language is always one of: @locked_languages', array('@locked_languages' => implode(', ', $locked_languages)))); } } } diff --git a/core/modules/content_translation/content_translation.module b/core/modules/content_translation/content_translation.module index 43127b0..5423079 100644 --- a/core/modules/content_translation/content_translation.module +++ b/core/modules/content_translation/content_translation.module @@ -953,7 +953,7 @@ function content_translation_language_configuration_element_validate($element, a // @todo Set the correct form element name as soon as the element parents // are correctly set. We should be using NestedArray::getValue() but for // now we cannot. - form_set_error('', t('"Show language selector" is not compatible with translating content that has default language: %choice. Either do not hide the language selector or pick a specific language.', array('%choice' => $locked_languages[$values['langcode']]))); + form_set_error('', $form_state, t('"Show language selector" is not compatible with translating content that has default language: %choice. Either do not hide the language selector or pick a specific language.', array('%choice' => $locked_languages[$values['langcode']]))); } } diff --git a/core/modules/content_translation/lib/Drupal/content_translation/ContentTranslationController.php b/core/modules/content_translation/lib/Drupal/content_translation/ContentTranslationController.php index 634043b..30e1922 100644 --- a/core/modules/content_translation/lib/Drupal/content_translation/ContentTranslationController.php +++ b/core/modules/content_translation/lib/Drupal/content_translation/ContentTranslationController.php @@ -414,11 +414,11 @@ function entityFormValidate($form, &$form_state) { $translation = $form_state['values']['content_translation']; // Validate the "authored by" field. if (!empty($translation['name']) && !($account = user_load_by_name($translation['name']))) { - form_set_error('content_translation][name', t('The translation authoring username %name does not exist.', array('%name' => $translation['name']))); + form_set_error('content_translation][name', $form_state, t('The translation authoring username %name does not exist.', array('%name' => $translation['name']))); } // Validate the "authored on" field. if (!empty($translation['created']) && strtotime($translation['created']) === FALSE) { - form_set_error('content_translation][created', t('You have to specify a valid translation authoring date.')); + form_set_error('content_translation][created', $form_state, t('You have to specify a valid translation authoring date.')); } } } diff --git a/core/modules/datetime/datetime.module b/core/modules/datetime/datetime.module index da33989..c1d28e5 100644 --- a/core/modules/datetime/datetime.module +++ b/core/modules/datetime/datetime.module @@ -104,7 +104,7 @@ function datetime_theme() { * The current state of the form. */ function datetime_datetime_widget_validate(&$element, &$form_state) { - if (!form_get_errors()) { + if (!form_get_errors($form_state)) { $input_exists = FALSE; $input = NestedArray::getValue($form_state['values'], $element['#parents'], $input_exists); if ($input_exists) { @@ -142,7 +142,7 @@ function datetime_datetime_widget_validate(&$element, &$form_state) { * The current state of the form. */ function datetime_datelist_widget_validate(&$element, &$form_state) { - if (!form_get_errors()) { + if (!form_get_errors($form_state)) { $input_exists = FALSE; $input = NestedArray::getValue($form_state['values'], $element['#parents'], $input_exists); if ($input_exists) { @@ -574,7 +574,7 @@ function datetime_datetime_validate($element, &$form_state) { // If there's empty input and the field is required, set an error. A // reminder of the required format in the message provides a good UX. elseif (empty($input['date']) && empty($input['time']) && $element['#required']) { - form_error($element, t('The %field date is required. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format)))); + form_error($element, $form_state, t('The %field date is required. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format)))); } else { // If the date is valid, set it. @@ -585,7 +585,7 @@ function datetime_datetime_validate($element, &$form_state) { // If the date is invalid, set an error. A reminder of the required // format in the message provides a good UX. else { - form_error($element, t('The %field date is invalid. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format)))); + form_error($element, $form_state, t('The %field date is invalid. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format)))); } } } @@ -921,7 +921,7 @@ function datetime_datelist_validate($element, &$form_state) { } // If there's empty input and the field is required, set an error. elseif (empty($input['year']) && empty($input['month']) && empty($input['day']) && $element['#required']) { - form_error($element, t('The %field date is required.')); + form_error($element, $form_state, t('The %field date is required.')); } else { // If the input is valid, set it. @@ -931,7 +931,7 @@ function datetime_datelist_validate($element, &$form_state) { } // If the input is invalid, set an error. else { - form_error($element, t('The %field date is invalid.')); + form_error($element, $form_state, t('The %field date is invalid.')); } } } diff --git a/core/modules/dblog/dblog.admin.inc b/core/modules/dblog/dblog.admin.inc index 9a5ef3b..a66c385 100644 --- a/core/modules/dblog/dblog.admin.inc +++ b/core/modules/dblog/dblog.admin.inc @@ -163,7 +163,7 @@ function dblog_filter_form($form) { */ function dblog_filter_form_validate($form, &$form_state) { if ($form_state['values']['op'] == t('Filter') && empty($form_state['values']['type']) && empty($form_state['values']['severity'])) { - form_set_error('type', t('You must select something to filter by.')); + form_set_error('type', $form_state, t('You must select something to filter by.')); } } diff --git a/core/modules/edit/lib/Drupal/edit/EditController.php b/core/modules/edit/lib/Drupal/edit/EditController.php index c63b956..39ced93 100644 --- a/core/modules/edit/lib/Drupal/edit/EditController.php +++ b/core/modules/edit/lib/Drupal/edit/EditController.php @@ -256,7 +256,7 @@ public function fieldForm(EntityInterface $entity, $field_name, $langcode, $view else { $response->addCommand(new FieldFormCommand(drupal_render($form))); - $errors = form_get_errors(); + $errors = form_get_errors($form_state); if (count($errors)) { $status_messages = array( '#theme' => 'status_messages' diff --git a/core/modules/edit/lib/Drupal/edit/Form/EditFieldForm.php b/core/modules/edit/lib/Drupal/edit/Form/EditFieldForm.php index f98f91e..ad9410d 100644 --- a/core/modules/edit/lib/Drupal/edit/Form/EditFieldForm.php +++ b/core/modules/edit/lib/Drupal/edit/Form/EditFieldForm.php @@ -155,7 +155,7 @@ public function validateForm(array &$form, array &$form_state) { if ($changed_field_name = $this->getChangedFieldName($entity)) { $changed_field_errors = $entity->$changed_field_name->validate(); if (count($changed_field_errors)) { - form_set_error('changed_field', $changed_field_errors[0]->getMessage()); + form_set_error('changed_field', $form_state, $changed_field_errors[0]->getMessage()); } } } diff --git a/core/modules/editor/editor.module b/core/modules/editor/editor.module index 4a560ee..7951f27 100644 --- a/core/modules/editor/editor.module +++ b/core/modules/editor/editor.module @@ -295,7 +295,7 @@ function editor_form_filter_admin_format_validate($form, &$form_state) { // selected a text editor and has then clicked 'Save configuration', we should // point out that the user must still configure the text editor. if ($form_state['values']['editor']['editor'] !== '' && empty($form_state['editor'])) { - form_set_error('editor][editor', t('You must configure the selected text editor.')); + form_set_error('editor][editor', $form_state, t('You must configure the selected text editor.')); } } diff --git a/core/modules/editor/lib/Drupal/editor/Form/EditorImageDialog.php b/core/modules/editor/lib/Drupal/editor/Form/EditorImageDialog.php index d7ef08c..05551e9 100644 --- a/core/modules/editor/lib/Drupal/editor/Form/EditorImageDialog.php +++ b/core/modules/editor/lib/Drupal/editor/Form/EditorImageDialog.php @@ -203,7 +203,7 @@ public function submitForm(array &$form, array &$form_state) { $form_state['values']['attributes']['data-editor-file-uuid'] = $file->uuid(); } - if (form_get_errors()) { + if (form_get_errors($form_state)) { unset($form['#prefix'], $form['#suffix']); $status_messages = array('#theme' => 'status_messages'); $output = drupal_render($form); diff --git a/core/modules/editor/lib/Drupal/editor/Form/EditorLinkDialog.php b/core/modules/editor/lib/Drupal/editor/Form/EditorLinkDialog.php index 42f47cb..9bc2948 100644 --- a/core/modules/editor/lib/Drupal/editor/Form/EditorLinkDialog.php +++ b/core/modules/editor/lib/Drupal/editor/Form/EditorLinkDialog.php @@ -81,7 +81,7 @@ public function buildForm(array $form, array &$form_state, FilterFormat $filter_ public function submitForm(array &$form, array &$form_state) { $response = new AjaxResponse(); - if (form_get_errors()) { + if (form_get_errors($form_state)) { unset($form['#prefix'], $form['#suffix']); $status_messages = array('#theme' => 'status_messages'); $output = drupal_render($form); diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php index 7419e93..99eba59 100644 --- a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php +++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php @@ -221,13 +221,13 @@ public function validateAutocompleteInput($input, &$element, &$form_state, $form if (empty($entities)) { if ($strict) { // Error if there are no entities available for a required field. - form_error($element, t('There are no entities matching "%value".', $params)); + form_error($element, $form_state, t('There are no entities matching "%value".', $params)); } } elseif (count($entities) > 5) { $params['@id'] = key($entities); // Error if there are more than 5 matching entities. - form_error($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)".', $params)); + form_error($element, $form_state, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)".', $params)); } elseif (count($entities) > 1) { // More helpful error if there are only a few matching entities. @@ -236,7 +236,7 @@ public function validateAutocompleteInput($input, &$element, &$form_state, $form $multiples[] = $name . ' (' . $id . ')'; } $params['@id'] = $id; - form_error($element, t('Multiple entities match this reference; "%multiple". Specify the one you want by appending the id in parentheses, like "@value (@id)".', array('%multiple' => implode('", "', $multiples)))); + form_error($element, $form_state, t('Multiple entities match this reference; "%multiple". Specify the one you want by appending the id in parentheses, like "@value (@id)".', array('%multiple' => implode('", "', $multiples)))); } else { // Take the one and only matching entity. diff --git a/core/modules/field_ui/lib/Drupal/field_ui/FieldOverview.php b/core/modules/field_ui/lib/Drupal/field_ui/FieldOverview.php index ec5a4c0..85c2e26 100644 --- a/core/modules/field_ui/lib/Drupal/field_ui/FieldOverview.php +++ b/core/modules/field_ui/lib/Drupal/field_ui/FieldOverview.php @@ -315,12 +315,12 @@ protected function validateAddNew(array $form, array &$form_state) { if (array_filter(array($field['label'], $field['field_name'], $field['type']))) { // Missing label. if (!$field['label']) { - form_set_error('fields][_add_new_field][label', $this->t('Add new field: you need to provide a label.')); + form_set_error('fields][_add_new_field][label', $form_state, $this->t('Add new field: you need to provide a label.')); } // Missing field name. if (!$field['field_name']) { - form_set_error('fields][_add_new_field][field_name', $this->t('Add new field: you need to provide a field name.')); + form_set_error('fields][_add_new_field][field_name', $form_state, $this->t('Add new field: you need to provide a field name.')); } // Field name validation. else { @@ -333,7 +333,7 @@ protected function validateAddNew(array $form, array &$form_state) { // Missing field type. if (!$field['type']) { - form_set_error('fields][_add_new_field][type', $this->t('Add new field: you need to select a field type.')); + form_set_error('fields][_add_new_field][type', $form_state, $this->t('Add new field: you need to select a field type.')); } } } @@ -359,12 +359,12 @@ protected function validateAddExisting(array $form, array &$form_state) { if (array_filter(array($field['label'], $field['field_name']))) { // Missing label. if (!$field['label']) { - form_set_error('fields][_add_existing_field][label', $this->t('Re-use existing field: you need to provide a label.')); + form_set_error('fields][_add_existing_field][label', $form_state, $this->t('Re-use existing field: you need to provide a label.')); } // Missing existing field name. if (!$field['field_name']) { - form_set_error('fields][_add_existing_field][field_name', $this->t('Re-use existing field: you need to select a field.')); + form_set_error('fields][_add_existing_field][field_name', $form_state, $this->t('Re-use existing field: you need to select a field.')); } } } diff --git a/core/modules/field_ui/lib/Drupal/field_ui/Form/FieldEditForm.php b/core/modules/field_ui/lib/Drupal/field_ui/Form/FieldEditForm.php index 062dd40..8950bd7 100644 --- a/core/modules/field_ui/lib/Drupal/field_ui/Form/FieldEditForm.php +++ b/core/modules/field_ui/lib/Drupal/field_ui/Form/FieldEditForm.php @@ -172,7 +172,7 @@ public function validateForm(array &$form, array &$form_state) { $cardinality = $form_state['values']['field']['cardinality']; $cardinality_number = $form_state['values']['field']['cardinality_number']; if ($cardinality === 'number' && empty($cardinality_number)) { - form_error($form['field']['cardinality_container']['cardinality_number'], $this->t('Number of values is required.')); + form_error($form['field']['cardinality_container']['cardinality_number'], $form_state, $this->t('Number of values is required.')); } } diff --git a/core/modules/file/file.module b/core/modules/file/file.module index 9bc1d85..8ac1514 100644 --- a/core/modules/file/file.module +++ b/core/modules/file/file.module @@ -729,6 +729,8 @@ function file_cron() { * @param $form_field_name * A string that is the associative array key of the upload form element in * the form array. + * @param array $form_state + * An associative array containing the current state of the form. * @param $validators * An optional, associative array of callback functions used to validate the * file. See file_validate() for a full discussion of the array format. @@ -764,7 +766,7 @@ function file_cron() { * - source: Path to the file before it is moved. * - destination: Path to the file after it is moved (same as 'uri'). */ -function file_save_upload($form_field_name, $validators = array(), $destination = FALSE, $delta = NULL, $replace = FILE_EXISTS_RENAME) { +function file_save_upload($form_field_name, array &$form_state, $validators = array(), $destination = FALSE, $delta = NULL, $replace = FILE_EXISTS_RENAME) { $user = \Drupal::currentUser(); static $upload_cache; @@ -922,7 +924,7 @@ function file_save_upload($form_field_name, $validators = array(), $destination else { $message .= ' ' . array_pop($errors); } - form_set_error($form_field_name, $message); + form_set_error($form_field_name, $form_state, $message); $files[$i] = FALSE; continue; } @@ -932,7 +934,7 @@ function file_save_upload($form_field_name, $validators = array(), $destination // operations. $file->uri = $file->destination; if (!drupal_move_uploaded_file($uploaded_files['files']['tmp_name'][$form_field_name][$i], $file->getFileUri())) { - form_set_error($form_field_name, t('File upload error. Could not move uploaded file.')); + form_set_error($form_field_name, $form_state, t('File upload error. Could not move uploaded file.')); watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri)); $files[$i] = FALSE; continue; @@ -1274,7 +1276,7 @@ function file_managed_file_process($element, &$form_state, $form) { * * This function is assigned as a #value_callback in file_element_info(). */ -function file_managed_file_value(&$element, $input = FALSE, $form_state = NULL) { +function file_managed_file_value(&$element, $input, &$form_state) { // Find the current value of this field. $fids = !empty($input['fids']) ? explode(' ', $input['fids']) : array(); foreach ($fids as $key => $fid) { @@ -1287,7 +1289,7 @@ function file_managed_file_value(&$element, $input = FALSE, $form_state = NULL) $return = $input; // Uploads take priority over all other values. - if ($files = file_managed_file_save_upload($element)) { + if ($files = file_managed_file_save_upload($element, $form_state)) { if ($element['#multiple']) { $fids = array_merge($fids, array_keys($files)); } @@ -1362,19 +1364,19 @@ function file_managed_file_validate(&$element, &$form_state) { if ($file->isPermanent()) { $references = file_usage()->listUsage($file); if (empty($references)) { - form_error($element, t('The file used in the !name field may not be referenced.', array('!name' => $element['#title']))); + form_error($element, $form_state, t('The file used in the !name field may not be referenced.', array('!name' => $element['#title']))); } } } else { - form_error($element, t('The file referenced by the !name field does not exist.', array('!name' => $element['#title']))); + form_error($element, $form_state, t('The file referenced by the !name field does not exist.', array('!name' => $element['#title']))); } } } // Check required property based on the FID. if ($element['#required'] && empty($element['fids']['#value']) && !in_array($clicked_button, array('upload_button', 'remove_button'))) { - form_error($element['upload'], t('!name field is required.', array('!name' => $element['#title']))); + form_error($element['upload'], $form_state, t('!name field is required.', array('!name' => $element['#title']))); } // Consolidate the array value of this field to array of FIDs. @@ -1452,12 +1454,14 @@ function file_managed_file_submit($form, &$form_state) { * * @param $element * The FAPI element whose values are being saved. + * @param array $form_state + * An associative array containing the current state of the form. * * @return * An array of file entities for each file that was saved, keyed by its file * ID, or FALSE if no files were saved. */ -function file_managed_file_save_upload($element) { +function file_managed_file_save_upload($element, array &$form_state) { $upload_name = implode('_', $element['#parents']); if (empty($_FILES['files']['name'][$upload_name])) { return FALSE; @@ -1466,7 +1470,7 @@ function file_managed_file_save_upload($element) { $destination = isset($element['#upload_location']) ? $element['#upload_location'] : NULL; if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) { watchdog('file', 'The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', array('%directory' => $destination, '!name' => $element['#field_name'])); - form_set_error($upload_name, t('The file could not be uploaded.')); + form_set_error($upload_name, $form_state, t('The file could not be uploaded.')); return FALSE; } @@ -1474,9 +1478,9 @@ function file_managed_file_save_upload($element) { $files_uploaded = $element['#multiple'] && count(array_filter($_FILES['files']['name'][$upload_name])) > 0; $files_uploaded |= !$element['#multiple'] && !empty($_FILES['files']['name'][$upload_name]); if ($files_uploaded) { - if (!$files = file_save_upload($upload_name, $element['#upload_validators'], $destination)) { + if (!$files = file_save_upload($upload_name, $form_state, $element['#upload_validators'], $destination)) { watchdog('file', 'The file upload failed. %upload', array('%upload' => $upload_name)); - form_set_error($upload_name, t('Files in the !name field were unable to be uploaded.', array('!name' => $element['#title']))); + form_set_error($upload_name, $form_state, t('Files in the !name field were unable to be uploaded.', array('!name' => $element['#title']))); return array(); } diff --git a/core/modules/file/lib/Drupal/file/Plugin/Field/FieldType/FileItem.php b/core/modules/file/lib/Drupal/file/Plugin/Field/FieldType/FileItem.php index 812fd0b..2173689 100644 --- a/core/modules/file/lib/Drupal/file/Plugin/Field/FieldType/FileItem.php +++ b/core/modules/file/lib/Drupal/file/Plugin/Field/FieldType/FileItem.php @@ -237,7 +237,7 @@ public static function validateExtensions($element, &$form_state) { $extensions = array_filter(explode(' ', $extensions)); $extensions = implode(' ', array_unique($extensions)); if (!preg_match('/^([a-z0-9]+([.][a-z0-9])* ?)+$/', $extensions)) { - form_error($element, t('The list of allowed extensions is not valid, be sure to exclude leading dots and to separate extensions with a comma or space.')); + form_error($element, $form_state, t('The list of allowed extensions is not valid, be sure to exclude leading dots and to separate extensions with a comma or space.')); } else { form_set_value($element, $extensions, $form_state); @@ -256,7 +256,7 @@ public static function validateExtensions($element, &$form_state) { */ public static function validateMaxFilesize($element, &$form_state) { if (!empty($element['#value']) && !is_numeric(parse_size($element['#value']))) { - form_error($element, t('The "!name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', array('!name' => t($element['title'])))); + form_error($element, $form_state, t('The "!name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', array('!name' => t($element['title'])))); } } diff --git a/core/modules/file/tests/file_test/lib/Drupal/file_test/Form/FileTestForm.php b/core/modules/file/tests/file_test/lib/Drupal/file_test/Form/FileTestForm.php index f2d6dc2..3c5f1fe 100644 --- a/core/modules/file/tests/file_test/lib/Drupal/file_test/Form/FileTestForm.php +++ b/core/modules/file/tests/file_test/lib/Drupal/file_test/Form/FileTestForm.php @@ -101,7 +101,7 @@ public function submitForm(array &$form, array &$form_state) { $validators['file_validate_extensions'] = array($form_state['values']['extensions']); } - $file = file_save_upload('file_test_upload', $validators, $destination, 0, $form_state['values']['file_test_replace']); + $file = file_save_upload('file_test_upload', $form_state, $validators, $destination, 0, $form_state['values']['file_test_replace']); if ($file) { $form_state['values']['file_test_upload'] = $file; drupal_set_message(t('File @filepath was uploaded.', array('@filepath' => $file->getFileUri()))); diff --git a/core/modules/filter/lib/Drupal/filter/FilterFormatFormControllerBase.php b/core/modules/filter/lib/Drupal/filter/FilterFormatFormControllerBase.php index fd79f02..002c1d5 100644 --- a/core/modules/filter/lib/Drupal/filter/FilterFormatFormControllerBase.php +++ b/core/modules/filter/lib/Drupal/filter/FilterFormatFormControllerBase.php @@ -232,7 +232,7 @@ public function validate(array $form, array &$form_state) { ->condition('name', $format_name) ->execute(); if ($format_exists) { - form_set_error('name', t('Text format names must be unique. A format named %name already exists.', array('%name' => $format_name))); + form_set_error('name', $form_state, t('Text format names must be unique. A format named %name already exists.', array('%name' => $format_name))); } } diff --git a/core/modules/forum/forum.module b/core/modules/forum/forum.module index e860181..0741ec8 100644 --- a/core/modules/forum/forum.module +++ b/core/modules/forum/forum.module @@ -227,7 +227,7 @@ function forum_uri($forum) { * Checks in particular that the node is assigned only a "leaf" term in the * forum taxonomy. */ -function forum_node_validate(EntityInterface $node, $form) { +function forum_node_validate(EntityInterface $node, $form, &$form_state) { if (\Drupal::service('forum_manager')->checkNodeType($node)) { // vocabulary is selected, not a "container" term. if (!$node->taxonomy_forums->isEmpty()) { @@ -241,7 +241,7 @@ function forum_node_validate(EntityInterface $node, $form) { } $term = $item->entity; if (!$term) { - form_set_error('taxonomy_forums', t('Select a forum.')); + form_set_error('taxonomy_forums', $form_state, t('Select a forum.')); continue; } $used = \Drupal::entityQuery('taxonomy_term') @@ -251,7 +251,7 @@ function forum_node_validate(EntityInterface $node, $form) { ->count() ->execute(); if ($used && !empty($term->forum_container->value)) { - form_set_error('taxonomy_forums', t('The item %forum is a forum container, not a forum. Select one of the forums below instead.', array('%forum' => $term->label()))); + form_set_error('taxonomy_forums', $form_state, t('The item %forum is a forum container, not a forum. Select one of the forums below instead.', array('%forum' => $term->label()))); } } } diff --git a/core/modules/image/image.field.inc b/core/modules/image/image.field.inc index 2663351..244f389 100644 --- a/core/modules/image/image.field.inc +++ b/core/modules/image/image.field.inc @@ -117,7 +117,7 @@ function _image_field_required_fields_validate($element, &$form_state) { } // Check if field is left emtpy. elseif (empty($image_field[$field])) { - form_error($element, t('The field !title is required', array('!title' => $element['#title']))); + form_error($element, $form_state, t('The field !title is required', array('!title' => $element['#title']))); return; } } diff --git a/core/modules/image/lib/Drupal/image/Form/ImageStyleEditForm.php b/core/modules/image/lib/Drupal/image/Form/ImageStyleEditForm.php index 1206213..d5c46de 100644 --- a/core/modules/image/lib/Drupal/image/Form/ImageStyleEditForm.php +++ b/core/modules/image/lib/Drupal/image/Form/ImageStyleEditForm.php @@ -156,7 +156,7 @@ public function form(array $form, array &$form_state) { */ public function effectValidate($form, &$form_state) { if (!$form_state['values']['new']) { - form_error($form['effects']['new']['new'], $this->t('Select an effect to add.')); + form_error($form['effects']['new']['new'], $form_state, $this->t('Select an effect to add.')); } } diff --git a/core/modules/image/lib/Drupal/image/Plugin/Field/FieldType/ImageItem.php b/core/modules/image/lib/Drupal/image/Plugin/Field/FieldType/ImageItem.php index fba7895..b697465 100644 --- a/core/modules/image/lib/Drupal/image/Plugin/Field/FieldType/ImageItem.php +++ b/core/modules/image/lib/Drupal/image/Plugin/Field/FieldType/ImageItem.php @@ -308,7 +308,7 @@ public static function validateResolution($element, &$form_state) { if (!empty($element['x']['#value']) || !empty($element['y']['#value'])) { foreach (array('x', 'y') as $dimension) { if (!$element[$dimension]['#value']) { - form_error($element[$dimension], t('Both a height and width value must be specified in the !name field.', array('!name' => $element['#title']))); + form_error($element[$dimension], $form_state, t('Both a height and width value must be specified in the !name field.', array('!name' => $element['#title']))); return; } } diff --git a/core/modules/image/lib/Drupal/image/Plugin/ImageEffect/RotateImageEffect.php b/core/modules/image/lib/Drupal/image/Plugin/ImageEffect/RotateImageEffect.php index 23c0560..571c5fa 100644 --- a/core/modules/image/lib/Drupal/image/Plugin/ImageEffect/RotateImageEffect.php +++ b/core/modules/image/lib/Drupal/image/Plugin/ImageEffect/RotateImageEffect.php @@ -129,7 +129,7 @@ public function getForm() { public function validateColorEffect(array $element, array &$form_state) { if ($element['#value'] != '') { if (!preg_match('/^#[0-9A-F]{3}([0-9A-F]{3})?$/', $element['#value'])) { - form_error($element, t('!name must be a hexadecimal color value.', array('!name' => $element['#title']))); + form_error($element, $form_state, t('!name must be a hexadecimal color value.', array('!name' => $element['#title']))); } } } diff --git a/core/modules/image/lib/Drupal/image/Plugin/ImageEffect/ScaleImageEffect.php b/core/modules/image/lib/Drupal/image/Plugin/ImageEffect/ScaleImageEffect.php index 87b0dac..1dae008 100644 --- a/core/modules/image/lib/Drupal/image/Plugin/ImageEffect/ScaleImageEffect.php +++ b/core/modules/image/lib/Drupal/image/Plugin/ImageEffect/ScaleImageEffect.php @@ -84,7 +84,7 @@ public function getForm() { */ public function validateScaleEffect(array $element, array &$form_state) { if (empty($element['width']['#value']) && empty($element['height']['#value'])) { - form_error($element, t('Width and height can not both be blank.')); + form_error($element, $form_state, t('Width and height can not both be blank.')); } } diff --git a/core/modules/language/lib/Drupal/language/Form/LanguageAddForm.php b/core/modules/language/lib/Drupal/language/Form/LanguageAddForm.php index 09420b0..64f3f97 100644 --- a/core/modules/language/lib/Drupal/language/Form/LanguageAddForm.php +++ b/core/modules/language/lib/Drupal/language/Form/LanguageAddForm.php @@ -124,11 +124,11 @@ public function validateCustom(array $form, array &$form_state) { $this->validateCommon($form['custom_language'], $form_state); if ($language = language_load($langcode)) { - form_error($form['custom_language']['langcode'], $this->t('The language %language (%langcode) already exists.', array('%language' => $language->name, '%langcode' => $langcode))); + form_error($form['custom_language']['langcode'], $form_state, $this->t('The language %language (%langcode) already exists.', array('%language' => $language->name, '%langcode' => $langcode))); } } else { - form_error($form['predefined_langcode'], $this->t('Use the Add language button to save a predefined language.')); + form_error($form['predefined_langcode'], $form_state, $this->t('Use the Add language button to save a predefined language.')); } } @@ -138,11 +138,11 @@ public function validateCustom(array $form, array &$form_state) { public function validatePredefined($form, &$form_state) { $langcode = $form_state['values']['predefined_langcode']; if ($langcode == 'custom') { - form_error($form['predefined_langcode'], $this->t('Fill in the language details and save the language with Add custom language.')); + form_error($form['predefined_langcode'], $form_state, $this->t('Fill in the language details and save the language with Add custom language.')); } else { if ($language = language_load($langcode)) { - form_error($form['predefined_langcode'], $this->t('The language %language (%langcode) already exists.', array('%language' => $language->name, '%langcode' => $langcode))); + form_error($form['predefined_langcode'], $form_state, $this->t('The language %language (%langcode) already exists.', array('%language' => $language->name, '%langcode' => $langcode))); } } } diff --git a/core/modules/language/lib/Drupal/language/Form/LanguageFormBase.php b/core/modules/language/lib/Drupal/language/Form/LanguageFormBase.php index b6d43ec..2b20c8d 100644 --- a/core/modules/language/lib/Drupal/language/Form/LanguageFormBase.php +++ b/core/modules/language/lib/Drupal/language/Form/LanguageFormBase.php @@ -70,10 +70,10 @@ public function commonForm(array &$form) { public function validateCommon(array $form, array &$form_state) { // Ensure sane field values for langcode and name. if (!isset($form['langcode_view']) && preg_match('@[^a-zA-Z_-]@', $form_state['values']['langcode'])) { - form_error($form['langcode'], $this->t('%field may only contain characters a-z, underscores, or hyphens.', array('%field' => $form['langcode']['#title']))); + form_error($form['langcode'], $form_state, $this->t('%field may only contain characters a-z, underscores, or hyphens.', array('%field' => $form['langcode']['#title']))); } if ($form_state['values']['name'] != check_plain($form_state['values']['name'])) { - form_error($form['name'], $this->t('%field cannot contain any markup.', array('%field' => $form['name']['#title']))); + form_error($form['name'], $form_state, $this->t('%field cannot contain any markup.', array('%field' => $form['name']['#title']))); } } diff --git a/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserForm.php b/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserForm.php index d5b991d..4a8ec2d 100644 --- a/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserForm.php +++ b/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserForm.php @@ -143,10 +143,10 @@ public function validateForm(array &$form, array &$form_state) { foreach ($mappings as $key => $data) { // Make sure browser_langcode is unique. if (array_key_exists($data['browser_langcode'], $unique_values)) { - form_set_error('mappings][' . $key . '][browser_langcode', $this->t('Browser language codes must be unique.')); + form_set_error('mappings][' . $key . '][browser_langcode', $form_state, $this->t('Browser language codes must be unique.')); } elseif (preg_match('/[^a-z\-]/', $data['browser_langcode'])) { - form_set_error('mappings][' . $key . '][browser_langcode', $this->t('Browser language codes can only contain lowercase letters and a hyphen(-).')); + form_set_error('mappings][' . $key . '][browser_langcode', $form_state, $this->t('Browser language codes can only contain lowercase letters and a hyphen(-).')); } $unique_values[$data['browser_langcode']] = $data['drupal_langcode']; } @@ -157,10 +157,10 @@ public function validateForm(array &$form, array &$form_state) { if (!empty($data['browser_langcode'])) { // Make sure browser_langcode is unique. if (array_key_exists($data['browser_langcode'], $unique_values)) { - form_set_error('mappings][' . $key . '][browser_langcode', $this->t('Browser language codes must be unique.')); + form_set_error('mappings][' . $key . '][browser_langcode', $form_state, $this->t('Browser language codes must be unique.')); } elseif (preg_match('/[^a-z\-]/', $data['browser_langcode'])) { - form_set_error('mappings][' . $key . '][browser_langcode', $this->t('Browser language codes can only contain lowercase letters and a hyphen(-).')); + form_set_error('mappings][' . $key . '][browser_langcode', $form_state, $this->t('Browser language codes can only contain lowercase letters and a hyphen(-).')); } $unique_values[$data['browser_langcode']] = $data['drupal_langcode']; } diff --git a/core/modules/language/lib/Drupal/language/Form/NegotiationUrlForm.php b/core/modules/language/lib/Drupal/language/Form/NegotiationUrlForm.php index 4a7adb0..9a6c267 100644 --- a/core/modules/language/lib/Drupal/language/Form/NegotiationUrlForm.php +++ b/core/modules/language/lib/Drupal/language/Form/NegotiationUrlForm.php @@ -106,18 +106,18 @@ public function validateForm(array &$form, array &$form_state) { if (!$language->default && $form_state['values']['language_negotiation_url_part'] == LANGUAGE_NEGOTIATION_URL_PREFIX) { // Throw a form error if the prefix is blank for a non-default language, // although it is required for selected negotiation type. - form_error($form['prefix'][$langcode], t('The prefix may only be left blank for the default language.')); + form_error($form['prefix'][$langcode], $form_state, t('The prefix may only be left blank for the default language.')); } } elseif (strpos($value, '/') !== FALSE) { // Throw a form error if the string contains a slash, // which would not work. - form_error($form['prefix'][$langcode], t('The prefix may not contain a slash.')); + form_error($form['prefix'][$langcode], $form_state, t('The prefix may not contain a slash.')); } elseif (isset($count[$value]) && $count[$value] > 1) { // Throw a form error if there are two languages with the same // domain/prefix. - form_error($form['prefix'][$langcode], t('The prefix for %language, %value, is not unique.', array('%language' => $language->name, '%value' => $value))); + form_error($form['prefix'][$langcode], $form_state, t('The prefix for %language, %value, is not unique.', array('%language' => $language->name, '%value' => $value))); } } @@ -130,13 +130,13 @@ public function validateForm(array &$form, array &$form_state) { if (!$language->default && $form_state['values']['language_negotiation_url_part'] == LANGUAGE_NEGOTIATION_URL_DOMAIN) { // Throw a form error if the domain is blank for a non-default language, // although it is required for selected negotiation type. - form_error($form['domain'][$langcode], t('The domain may only be left blank for the default language.')); + form_error($form['domain'][$langcode], $form_state, t('The domain may only be left blank for the default language.')); } } elseif (isset($count[$value]) && $count[$value] > 1) { // Throw a form error if there are two languages with the same // domain/domain. - form_error($form['domain'][$langcode], t('The domain for %language, %value, is not unique.', array('%language' => $language->name, '%value' => $value))); + form_error($form['domain'][$langcode], $form_state, t('The domain for %language, %value, is not unique.', array('%language' => $language->name, '%value' => $value))); } } @@ -147,7 +147,7 @@ public function validateForm(array &$form, array &$form_state) { // Ensure we have exactly one protocol when checking the hostname. $host = 'http://' . str_replace(array('http://', 'https://'), '', $value); if (parse_url($host, PHP_URL_HOST) != $value) { - form_error($form['domain'][$langcode], t('The domain for %language may only contain the domain name, not a protocol and/or port.', array('%language' => $name))); + form_error($form['domain'][$langcode], $form_state, t('The domain for %language may only contain the domain name, not a protocol and/or port.', array('%language' => $name))); } } } diff --git a/core/modules/link/lib/Drupal/link/Plugin/Field/FieldWidget/LinkWidget.php b/core/modules/link/lib/Drupal/link/Plugin/Field/FieldWidget/LinkWidget.php index 1b3ccde..9c5e3cb 100644 --- a/core/modules/link/lib/Drupal/link/Plugin/Field/FieldWidget/LinkWidget.php +++ b/core/modules/link/lib/Drupal/link/Plugin/Field/FieldWidget/LinkWidget.php @@ -134,7 +134,7 @@ public function settingsSummary() { function validateTitle(&$element, &$form_state, $form) { if ($element['url']['#value'] !== '' && $element['title']['#value'] === '') { $element['title']['#required'] = TRUE; - form_error($element['title'], t('!name field is required.', array('!name' => $element['title']['#title']))); + form_error($element['title'], $form_state, t('!name field is required.', array('!name' => $element['title']['#title']))); } } } diff --git a/core/modules/locale/lib/Drupal/locale/Form/LocaleSettingsForm.php b/core/modules/locale/lib/Drupal/locale/Form/LocaleSettingsForm.php index 7710f20..3d4a410 100644 --- a/core/modules/locale/lib/Drupal/locale/Form/LocaleSettingsForm.php +++ b/core/modules/locale/lib/Drupal/locale/Form/LocaleSettingsForm.php @@ -93,7 +93,7 @@ public function validateForm(array &$form, array &$form_state) { parent::validateForm($form, $form_state); if (empty($form['#translation_directory']) && $form_state['values']['use_source'] == LOCALE_TRANSLATION_USE_SOURCE_LOCAL) { - form_set_error('use_source', t('You have selected local translation source, but no Interface translation directory was configured.', array('@url' => url('admin/config/media/file-system')))); + form_set_error('use_source', $form_state, t('You have selected local translation source, but no Interface translation directory was configured.', array('@url' => url('admin/config/media/file-system')))); } } diff --git a/core/modules/locale/lib/Drupal/locale/Form/TranslateEditForm.php b/core/modules/locale/lib/Drupal/locale/Form/TranslateEditForm.php index a80fa91..24456a8 100644 --- a/core/modules/locale/lib/Drupal/locale/Form/TranslateEditForm.php +++ b/core/modules/locale/lib/Drupal/locale/Form/TranslateEditForm.php @@ -166,8 +166,8 @@ public function validateForm(array &$form, array &$form_state) { foreach ($form_state['values']['strings'] as $lid => $translations) { foreach ($translations['translations'] as $key => $value) { if (!locale_string_is_safe($value)) { - form_set_error("strings][$lid][translations][$key", $this->t('The submitted string contains disallowed HTML: %string', array('%string' => $value))); - form_set_error("translations][$langcode][$key", $this->t('The submitted string contains disallowed HTML: %string', array('%string' => $value))); + form_set_error("strings][$lid][translations][$key", $form_state, $this->t('The submitted string contains disallowed HTML: %string', array('%string' => $value))); + form_set_error("translations][$langcode][$key", $form_state, $this->t('The submitted string contains disallowed HTML: %string', array('%string' => $value))); watchdog('locale', 'Attempted submission of a translation string with disallowed HTML: %string', array('%string' => $value), WATCHDOG_WARNING); } } diff --git a/core/modules/locale/locale.bulk.inc b/core/modules/locale/locale.bulk.inc index a0eb62c..078e409 100644 --- a/core/modules/locale/locale.bulk.inc +++ b/core/modules/locale/locale.bulk.inc @@ -111,7 +111,7 @@ function locale_translate_import_form($form, &$form_state) { */ function locale_translate_import_form_submit($form, &$form_state) { // Ensure we have the file uploaded. - if ($file = file_save_upload('file', $form['file']['#upload_validators'], 'translations://', 0)) { + if ($file = file_save_upload('file', $form_state, $form['file']['#upload_validators'], 'translations://', 0)) { // Add language, if not yet supported. $language = language_load($form_state['values']['langcode']); @@ -132,7 +132,7 @@ function locale_translate_import_form_submit($form, &$form_state) { batch_set($batch); } else { - form_set_error('file', t('File to import not found.')); + form_set_error('file', $form_state, t('File to import not found.')); $form_state['rebuild'] = TRUE; return; } diff --git a/core/modules/locale/locale.pages.inc b/core/modules/locale/locale.pages.inc index 0daa74c..462f6fa 100644 --- a/core/modules/locale/locale.pages.inc +++ b/core/modules/locale/locale.pages.inc @@ -180,7 +180,7 @@ function locale_translation_status_form($form, &$form_state) { function locale_translation_status_form_validate($form, &$form_state) { // Check if a language has been selected. 'tableselect' doesn't. if (!array_filter($form_state['values']['langcodes'])) { - form_set_error('', t('Select a language to update.')); + form_set_error('', $form_state, t('Select a language to update.')); } } diff --git a/core/modules/menu_link/lib/Drupal/menu_link/MenuLinkFormController.php b/core/modules/menu_link/lib/Drupal/menu_link/MenuLinkFormController.php index ef70aff..7c39219 100644 --- a/core/modules/menu_link/lib/Drupal/menu_link/MenuLinkFormController.php +++ b/core/modules/menu_link/lib/Drupal/menu_link/MenuLinkFormController.php @@ -234,7 +234,7 @@ public function validate(array $form, array &$form_state) { } } if (!trim($menu_link->link_path) || !drupal_valid_path($menu_link->link_path, TRUE)) { - form_set_error('link_path', t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $menu_link->link_path))); + form_set_error('link_path', $form_state, t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $menu_link->link_path))); } parent::validate($form, $form_state); diff --git a/core/modules/node/lib/Drupal/node/NodeFormController.php b/core/modules/node/lib/Drupal/node/NodeFormController.php index 659777a..1af5932 100644 --- a/core/modules/node/lib/Drupal/node/NodeFormController.php +++ b/core/modules/node/lib/Drupal/node/NodeFormController.php @@ -251,7 +251,7 @@ protected function actions(array $form, array &$form_state) { $node = $this->entity; $preview_mode = $this->settings['preview']; - $element['submit']['#access'] = $preview_mode != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])); + $element['submit']['#access'] = $preview_mode != DRUPAL_REQUIRED || (!form_get_errors($form_state) && isset($form_state['node_preview'])); // If saving is an option, privileged users get dedicated form submit // buttons to adjust the publishing status while saving in one go. @@ -330,7 +330,7 @@ public function validate(array $form, array &$form_state) { $node = $this->buildEntity($form, $form_state); if ($node->id() && (node_last_changed($node->id(), $this->getFormLangcode($form_state)) > $node->getChangedTime())) { - form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.')); + form_set_error('changed', $form_state, t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.')); } // Validate the "authored by" field. @@ -338,14 +338,14 @@ public function validate(array $form, array &$form_state) { // The use of empty() is mandatory in the context of usernames // as the empty string denotes the anonymous user. In case we // are dealing with an anonymous user we set the user ID to 0. - form_set_error('name', t('The username %name does not exist.', array('%name' => $form_state['values']['name']))); + form_set_error('name', $form_state, t('The username %name does not exist.', array('%name' => $form_state['values']['name']))); } // Validate the "authored on" field. // The date element contains the date object. $date = $node->date instanceof DrupalDateTime ? $node->date : new DrupalDateTime($node->date); if ($date->hasErrors()) { - form_set_error('date', t('You have to specify a valid date.')); + form_set_error('date', $form_state, t('You have to specify a valid date.')); } // Invoke hook_node_validate() for validation needed by modules. @@ -403,7 +403,7 @@ public function preview(array $form, array &$form_state) { // classes. module_load_include('inc', 'node', 'node.pages'); drupal_set_title(t('Preview'), PASS_THROUGH); - $form_state['node_preview'] = node_preview($this->entity); + $form_state['node_preview'] = node_preview($this->entity, $form_state); $form_state['rebuild'] = TRUE; } diff --git a/core/modules/node/lib/Drupal/node/NodeTypeFormController.php b/core/modules/node/lib/Drupal/node/NodeTypeFormController.php index ef94963..361417c 100644 --- a/core/modules/node/lib/Drupal/node/NodeTypeFormController.php +++ b/core/modules/node/lib/Drupal/node/NodeTypeFormController.php @@ -182,7 +182,7 @@ public function validate(array $form, array &$form_state) { $id = trim($form_state['values']['type']); // '0' is invalid, since elsewhere we check it using empty(). if ($id == '0') { - form_set_error('type', t("Invalid machine-readable name. Enter a name other than %invalid.", array('%invalid' => $id))); + form_set_error('type', $form_state, t("Invalid machine-readable name. Enter a name other than %invalid.", array('%invalid' => $id))); } } diff --git a/core/modules/node/lib/Drupal/node/Plugin/Action/AssignOwnerNode.php b/core/modules/node/lib/Drupal/node/Plugin/Action/AssignOwnerNode.php index ced712e..50b6c76 100644 --- a/core/modules/node/lib/Drupal/node/Plugin/Action/AssignOwnerNode.php +++ b/core/modules/node/lib/Drupal/node/Plugin/Action/AssignOwnerNode.php @@ -122,7 +122,7 @@ public function buildConfigurationForm(array $form, array &$form_state) { public function validateConfigurationForm(array &$form, array &$form_state) { $exists = (bool) $this->connection->queryRange('SELECT 1 FROM {users} WHERE name = :name', 0, 1, array(':name' => $form_state['values']['owner_name']))->fetchField(); if (!$exists) { - form_set_error('owner_name', t('Enter a valid username.')); + form_set_error('owner_name', $form_state, t('Enter a valid username.')); } } diff --git a/core/modules/node/lib/Drupal/node/Plugin/Condition/NodeType.php b/core/modules/node/lib/Drupal/node/Plugin/Condition/NodeType.php index b9d2a9c..59ce544 100644 --- a/core/modules/node/lib/Drupal/node/Plugin/Condition/NodeType.php +++ b/core/modules/node/lib/Drupal/node/Plugin/Condition/NodeType.php @@ -54,7 +54,7 @@ public function buildForm(array $form, array &$form_state) { public function validateForm(array &$form, array &$form_state) { foreach ($form_state['values']['bundles'] as $bundle) { if (!in_array($bundle, array_keys(node_type_get_types()))) { - form_set_error('bundles', t('You have chosen an invalid node bundle, please check your selection and try again.')); + form_set_error('bundles', $form_state, t('You have chosen an invalid node bundle, please check your selection and try again.')); } } } diff --git a/core/modules/node/lib/Drupal/node/Plugin/views/field/NodeBulkForm.php b/core/modules/node/lib/Drupal/node/Plugin/views/field/NodeBulkForm.php index e248868..418610a 100644 --- a/core/modules/node/lib/Drupal/node/Plugin/views/field/NodeBulkForm.php +++ b/core/modules/node/lib/Drupal/node/Plugin/views/field/NodeBulkForm.php @@ -37,7 +37,7 @@ public function __construct(array $configuration, $plugin_id, array $plugin_defi public function views_form_validate(&$form, &$form_state) { $selected = array_filter($form_state['values'][$this->options['id']]); if (empty($selected)) { - form_set_error('', t('No items selected.')); + form_set_error('', $form_state, t('No items selected.')); } } diff --git a/core/modules/node/node.api.php b/core/modules/node/node.api.php index 807ee49..cfc9240 100644 --- a/core/modules/node/node.api.php +++ b/core/modules/node/node.api.php @@ -723,7 +723,7 @@ function hook_node_update_index(\Drupal\Core\Entity\EntityInterface $node, $lang * Note: Changes made to the $node object within your hook implementation will * have no effect. The preferred method to change a node's content is to use * hook_node_presave() instead. If it is really necessary to change the node at - * the validate stage, you can use form_set_value(). + * the validate stage, $form_state, you can use form_set_value(). * * @param \Drupal\Core\Entity\EntityInterface $node * The node being validated. @@ -737,7 +737,7 @@ function hook_node_update_index(\Drupal\Core\Entity\EntityInterface $node, $lang function hook_node_validate(\Drupal\Core\Entity\EntityInterface $node, $form, &$form_state) { if (isset($node->end) && isset($node->start)) { if ($node->start > $node->end) { - form_set_error('time', t('An event may not end before it starts.')); + form_set_error('time', $form_state, t('An event may not end before it starts.')); } } } diff --git a/core/modules/node/node.pages.inc b/core/modules/node/node.pages.inc index 53dc99a..0a010f9 100644 --- a/core/modules/node/node.pages.inc +++ b/core/modules/node/node.pages.inc @@ -110,13 +110,13 @@ function node_add($node_type) { * * @see node_form_build_preview() */ -function node_preview(NodeInterface $node) { +function node_preview(NodeInterface $node, array &$form_state) { if (node_access('create', $node) || node_access('update', $node)) { $node->changed = REQUEST_TIME; // Display a preview of the node. - if (!form_get_errors()) { + if (!form_get_errors($form_state)) { $node->in_preview = TRUE; $node_preview = array( '#theme' => 'node_preview', diff --git a/core/modules/options/lib/Drupal/options/Plugin/Field/FieldWidget/OptionsWidgetBase.php b/core/modules/options/lib/Drupal/options/Plugin/Field/FieldWidget/OptionsWidgetBase.php index 166f476..baa3067 100644 --- a/core/modules/options/lib/Drupal/options/Plugin/Field/FieldWidget/OptionsWidgetBase.php +++ b/core/modules/options/lib/Drupal/options/Plugin/Field/FieldWidget/OptionsWidgetBase.php @@ -80,7 +80,7 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen */ public static function validateElement(array $element, array &$form_state) { if ($element['#required'] && $element['#value'] == '_none') { - form_error($element, t('!name field is required.', array('!name' => $element['#title']))); + form_error($element, $form_state, t('!name field is required.', array('!name' => $element['#title']))); } // Massage submitted form values. diff --git a/core/modules/options/options.module b/core/modules/options/options.module index dbe02e8..05af8ce 100644 --- a/core/modules/options/options.module +++ b/core/modules/options/options.module @@ -171,21 +171,21 @@ function options_field_settings_form_validate_allowed_values($element, &$form_st $values = options_extract_allowed_values($element['#value'], $field_type, $generate_keys); if (!is_array($values)) { - form_error($element, t('Allowed values list: invalid input.')); + form_error($element, $form_state, t('Allowed values list: invalid input.')); } else { // Check that keys are valid for the field type. foreach ($values as $key => $value) { if ($field_type == 'list_integer' && !preg_match('/^-?\d+$/', $key)) { - form_error($element, t('Allowed values list: keys must be integers.')); + form_error($element, $form_state, t('Allowed values list: keys must be integers.')); break; } if ($field_type == 'list_float' && !is_numeric($key)) { - form_error($element, t('Allowed values list: each key must be a valid integer or decimal.')); + form_error($element, $form_state, t('Allowed values list: each key must be a valid integer or decimal.')); break; } elseif ($field_type == 'list_text' && drupal_strlen($key) > 255) { - form_error($element, t('Allowed values list: each key must be a string at most 255 characters long.')); + form_error($element, $form_state, t('Allowed values list: each key must be a string at most 255 characters long.')); break; } } @@ -194,7 +194,7 @@ function options_field_settings_form_validate_allowed_values($element, &$form_st if ($has_data) { $lost_keys = array_diff(array_keys($field->getFieldSetting('allowed_values')), array_keys($values)); if (_options_values_in_use($field, $lost_keys)) { - form_error($element, t('Allowed values list: some values are being removed while currently in use.')); + form_error($element, $form_state, t('Allowed values list: some values are being removed while currently in use.')); } } diff --git a/core/modules/path/path.admin.inc b/core/modules/path/path.admin.inc index de338a2..b2941a0 100644 --- a/core/modules/path/path.admin.inc +++ b/core/modules/path/path.admin.inc @@ -241,10 +241,10 @@ function path_admin_form_validate($form, &$form_state) { ->fetchField(); if ($has_alias) { - form_set_error('alias', t('The alias %alias is already in use in this language.', array('%alias' => $alias))); + form_set_error('alias', $form_state, t('The alias %alias is already in use in this language.', array('%alias' => $alias))); } if (!drupal_valid_path($source)) { - form_set_error('source', t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $source))); + form_set_error('source', $form_state, t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $source))); } } diff --git a/core/modules/path/path.module b/core/modules/path/path.module index a965e9d..d33f881 100644 --- a/core/modules/path/path.module +++ b/core/modules/path/path.module @@ -164,7 +164,7 @@ function path_form_element_validate($element, &$form_state, $complete_form) { $query->addExpression('1'); $query->range(0, 1); if ($query->execute()->fetchField()) { - form_error($element, t('The alias is already in use.')); + form_error($element, $form_state, t('The alias is already in use.')); } } } diff --git a/core/modules/picture/lib/Drupal/picture/PictureMappingFormController.php b/core/modules/picture/lib/Drupal/picture/PictureMappingFormController.php index 00f5b9f..2601a75 100644 --- a/core/modules/picture/lib/Drupal/picture/PictureMappingFormController.php +++ b/core/modules/picture/lib/Drupal/picture/PictureMappingFormController.php @@ -125,7 +125,7 @@ public function validate(array $form, array &$form_state) { } // Make sure at least one mapping is defined. elseif (!$picture_mapping->isNew() && !$picture_mapping->hasMappings()) { - form_set_error('mappings', $this->t('Please select at least one mapping.')); + form_set_error('mappings', $form_state, $this->t('Please select at least one mapping.')); } } } diff --git a/core/modules/rest/lib/Drupal/rest/Plugin/views/row/DataFieldRow.php b/core/modules/rest/lib/Drupal/rest/Plugin/views/row/DataFieldRow.php index 60b244c..73291ca 100644 --- a/core/modules/rest/lib/Drupal/rest/Plugin/views/row/DataFieldRow.php +++ b/core/modules/rest/lib/Drupal/rest/Plugin/views/row/DataFieldRow.php @@ -115,7 +115,7 @@ public function buildOptionsForm(&$form, &$form_state) { */ public function validateAliasName($element, &$form_state) { if (preg_match('@[^A-Za-z0-9_-]+@', $element['#value'])) { - form_error($element, t('The machine-readable name must contain only letters, numbers, dashes and underscores.')); + form_error($element, $form_state, t('The machine-readable name must contain only letters, numbers, dashes and underscores.')); } } @@ -129,7 +129,7 @@ public function validateOptionsForm(&$form, &$form_state) { // If array filter returns empty, no values have been entered. Unique keys // should only be validated if we have some. if (($filtered = array_filter($aliases)) && (array_unique($filtered) !== $filtered)) { - form_set_error('aliases', t('All field aliases must be unique')); + form_set_error('aliases', $form_state, t('All field aliases must be unique')); } } diff --git a/core/modules/search/lib/Drupal/search/Form/SearchBlockForm.php b/core/modules/search/lib/Drupal/search/Form/SearchBlockForm.php index c2f14e7..bb4c9f7 100644 --- a/core/modules/search/lib/Drupal/search/Form/SearchBlockForm.php +++ b/core/modules/search/lib/Drupal/search/Form/SearchBlockForm.php @@ -58,7 +58,7 @@ public function submitForm(array &$form, array &$form_state) { // "field is required" because the search keywords field has no title. // The error message would also complain about a missing #title field.) if ($form_state['values']['search_block_form'] == '') { - form_set_error('keys', $this->t('Please enter some keywords.')); + form_set_error('keys', $form_state, $this->t('Please enter some keywords.')); } $form_id = $form['form_id']['#value']; @@ -72,7 +72,7 @@ public function submitForm(array &$form, array &$form_state) { ); } else { - form_set_error(NULL, $this->t('Search is currently disabled.'), 'error'); + form_set_error(NULL, $form_state, $this->t('Search is currently disabled.'), 'error'); } } } diff --git a/core/modules/search/lib/Drupal/search/Form/SearchForm.php b/core/modules/search/lib/Drupal/search/Form/SearchForm.php index 4101502..69022dd 100644 --- a/core/modules/search/lib/Drupal/search/Form/SearchForm.php +++ b/core/modules/search/lib/Drupal/search/Form/SearchForm.php @@ -112,7 +112,7 @@ public function validateForm(array &$form, array &$form_state) { public function submitForm(array &$form, array &$form_state) { $keys = $form_state['values']['processed_keys']; if ($keys == '') { - form_set_error('keys', t('Please enter some keywords.')); + form_set_error('keys', $form_state, t('Please enter some keywords.')); // Fall through to the form redirect. } diff --git a/core/modules/search/lib/Drupal/search/Form/SearchSettingsForm.php b/core/modules/search/lib/Drupal/search/Form/SearchSettingsForm.php index 0bf795a..0ceef4b 100644 --- a/core/modules/search/lib/Drupal/search/Form/SearchSettingsForm.php +++ b/core/modules/search/lib/Drupal/search/Form/SearchSettingsForm.php @@ -218,7 +218,7 @@ public function validateForm(array &$form, array &$form_state) { $new_plugins = array_filter($form_state['values']['active_plugins']); $default = $form_state['values']['default_plugin']; if (!in_array($default, $new_plugins, TRUE)) { - form_set_error('default_plugin', $this->t('Your default search plugin is not selected as an active plugin.')); + form_set_error('default_plugin', $form_state, $this->t('Your default search plugin is not selected as an active plugin.')); } } // Handle per-plugin validation logic. diff --git a/core/modules/search/lib/Drupal/search/Plugin/views/filter/Search.php b/core/modules/search/lib/Drupal/search/Plugin/views/filter/Search.php index 7d9f6cc..2726364 100644 --- a/core/modules/search/lib/Drupal/search/Plugin/views/filter/Search.php +++ b/core/modules/search/lib/Drupal/search/Plugin/views/filter/Search.php @@ -85,7 +85,7 @@ public function validateExposed(&$form, &$form_state) { if (!empty($form_state['values'][$key])) { $this->query_parse_search_expression($form_state['values'][$key]); if (count($this->search_query->words()) == 0) { - form_set_error($key, format_plural(\Drupal::config('search.settings')->get('index.minimum_word_size'), 'You must include at least one positive keyword with 1 character or more.', 'You must include at least one positive keyword with @count characters or more.')); + form_set_error($key, $form_state, format_plural(\Drupal::config('search.settings')->get('index.minimum_word_size'), 'You must include at least one positive keyword with 1 character or more.', 'You must include at least one positive keyword with @count characters or more.')); } } } diff --git a/core/modules/search/lib/Drupal/search/SearchQuery.php b/core/modules/search/lib/Drupal/search/SearchQuery.php index a331a4a..9458c26 100644 --- a/core/modules/search/lib/Drupal/search/SearchQuery.php +++ b/core/modules/search/lib/Drupal/search/SearchQuery.php @@ -325,7 +325,7 @@ public function executeFirstPass() { $this->parseSearchExpression(); if (count($this->words) == 0) { - form_set_error('keys', format_plural(\Drupal::config('search.settings')->get('index.minimum_word_size'), 'You must include at least one positive keyword with 1 character or more.', 'You must include at least one positive keyword with @count characters or more.')); + form_set_error('keys', $form_state, format_plural(\Drupal::config('search.settings')->get('index.minimum_word_size'), 'You must include at least one positive keyword with 1 character or more.', 'You must include at least one positive keyword with @count characters or more.')); return FALSE; } if ($this->expressionsIgnored) { diff --git a/core/modules/shortcut/lib/Drupal/shortcut/ShortcutSetFormController.php b/core/modules/shortcut/lib/Drupal/shortcut/ShortcutSetFormController.php index 8f89a05..b83bbaf 100644 --- a/core/modules/shortcut/lib/Drupal/shortcut/ShortcutSetFormController.php +++ b/core/modules/shortcut/lib/Drupal/shortcut/ShortcutSetFormController.php @@ -65,7 +65,7 @@ public function validate(array $form, array &$form_state) { $entity = $this->entity; // Check to prevent a duplicate title. if ($form_state['values']['label'] != $entity->label() && shortcut_set_title_exists($form_state['values']['label'])) { - form_set_error('label', t('The shortcut set %name already exists. Choose another name.', array('%name' => $form_state['values']['label']))); + form_set_error('label', $form_state, t('The shortcut set %name already exists. Choose another name.', array('%name' => $form_state['values']['label']))); } } diff --git a/core/modules/shortcut/shortcut.admin.inc b/core/modules/shortcut/shortcut.admin.inc index ab998a7..95fc18d 100644 --- a/core/modules/shortcut/shortcut.admin.inc +++ b/core/modules/shortcut/shortcut.admin.inc @@ -120,11 +120,11 @@ function shortcut_set_switch_validate($form, &$form_state) { if ($form_state['values']['set'] == 'new') { // Check to prevent creating a shortcut set with an empty title. if (trim($form_state['values']['label']) == '') { - form_set_error('new', t('The new set label is required.')); + form_set_error('new', $form_state, t('The new set label is required.')); } // Check to prevent a duplicate title. if (shortcut_set_title_exists($form_state['values']['label'])) { - form_set_error('label', t('The shortcut set %name already exists. Choose another name.', array('%name' => $form_state['values']['label']))); + form_set_error('label', $form_state, t('The shortcut set %name already exists. Choose another name.', array('%name' => $form_state['values']['label']))); } } } @@ -293,7 +293,7 @@ function _shortcut_link_form_elements($shortcut_link = NULL) { */ function shortcut_link_edit_validate($form, &$form_state) { if (!shortcut_valid_link($form_state['values']['shortcut_link']['link_path'])) { - form_set_error('shortcut_link][link_path', t('The link must correspond to a valid path on the site.')); + form_set_error('shortcut_link][link_path', $form_state, t('The link must correspond to a valid path on the site.')); } } diff --git a/core/modules/simpletest/lib/Drupal/simpletest/Form/SimpletestSettingsForm.php b/core/modules/simpletest/lib/Drupal/simpletest/Form/SimpletestSettingsForm.php index 62157bd..f54dd6c 100644 --- a/core/modules/simpletest/lib/Drupal/simpletest/Form/SimpletestSettingsForm.php +++ b/core/modules/simpletest/lib/Drupal/simpletest/Form/SimpletestSettingsForm.php @@ -97,7 +97,7 @@ public function validateForm(array &$form, array &$form_state) { // If a password was provided but a username wasn't, the credentials are // incorrect, so throw an error. if (empty($form_state['values']['simpletest_httpauth_username']) && !empty($form_state['values']['simpletest_httpauth_password'])) { - form_set_error('simpletest_httpauth_username', $this->t('HTTP authentication credentials must include a username in addition to a password.')); + form_set_error('simpletest_httpauth_username', $form_state, $this->t('HTTP authentication credentials must include a username in addition to a password.')); } parent::validateForm($form, $form_state); diff --git a/core/modules/system/lib/Drupal/system/Form/DateFormatFormBase.php b/core/modules/system/lib/Drupal/system/Form/DateFormatFormBase.php index 3b6f347..d8a69b5 100644 --- a/core/modules/system/lib/Drupal/system/Form/DateFormatFormBase.php +++ b/core/modules/system/lib/Drupal/system/Form/DateFormatFormBase.php @@ -191,7 +191,7 @@ public function validate(array $form, array &$form_state) { $pattern = trim($form_state['values']['date_format_pattern']); foreach ($this->dateFormatStorage->loadMultiple() as $format) { if ($format->getPattern() == $pattern && ($this->entity->isNew() || $format->id() != $this->entity->id())) { - form_set_error('date_format_pattern', t('This format already exists. Enter a unique format string.')); + form_set_error('date_format_pattern', $form_state, t('This format already exists. Enter a unique format string.')); continue; } } diff --git a/core/modules/system/lib/Drupal/system/Form/SiteInformationForm.php b/core/modules/system/lib/Drupal/system/Form/SiteInformationForm.php index f211126..fdc180c 100644 --- a/core/modules/system/lib/Drupal/system/Form/SiteInformationForm.php +++ b/core/modules/system/lib/Drupal/system/Form/SiteInformationForm.php @@ -144,7 +144,7 @@ public function validateForm(array &$form, array &$form_state) { } // Validate front page path. if (!drupal_valid_path($form_state['values']['site_frontpage'])) { - form_set_error('site_frontpage', t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state['values']['site_frontpage']))); + form_set_error('site_frontpage', $form_state, t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state['values']['site_frontpage']))); } // Get the normal paths of both error pages. if (!empty($form_state['values']['site_403'])) { @@ -155,11 +155,11 @@ public function validateForm(array &$form, array &$form_state) { } // Validate 403 error path. if (!empty($form_state['values']['site_403']) && !drupal_valid_path($form_state['values']['site_403'])) { - form_set_error('site_403', t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state['values']['site_403']))); + form_set_error('site_403', $form_state, t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state['values']['site_403']))); } // Validate 404 error path. if (!empty($form_state['values']['site_404']) && !drupal_valid_path($form_state['values']['site_404'])) { - form_set_error('site_404', t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state['values']['site_404']))); + form_set_error('site_404', $form_state, t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state['values']['site_404']))); } parent::validateForm($form, $form_state); diff --git a/core/modules/system/lib/Drupal/system/Form/ThemeSettingsForm.php b/core/modules/system/lib/Drupal/system/Form/ThemeSettingsForm.php index 8c46595..39d0caa 100644 --- a/core/modules/system/lib/Drupal/system/Form/ThemeSettingsForm.php +++ b/core/modules/system/lib/Drupal/system/Form/ThemeSettingsForm.php @@ -323,7 +323,7 @@ public function validateForm(array &$form, array &$form_state) { $validators = array('file_validate_is_image' => array()); // Check for a new uploaded logo. - $file = file_save_upload('logo_upload', $validators, FALSE, 0); + $file = file_save_upload('logo_upload', $form_state, $validators, FALSE, 0); if (isset($file)) { // File upload was attempted. if ($file) { @@ -332,14 +332,14 @@ public function validateForm(array &$form, array &$form_state) { } else { // File upload failed. - form_set_error('logo_upload', t('The logo could not be uploaded.')); + form_set_error('logo_upload', $form_state, t('The logo could not be uploaded.')); } } $validators = array('file_validate_extensions' => array('ico png gif jpg jpeg apng svg')); // Check for a new uploaded favicon. - $file = file_save_upload('favicon_upload', $validators, FALSE, 0); + $file = file_save_upload('favicon_upload', $form_state, $validators, FALSE, 0); if (isset($file)) { // File upload was attempted. if ($file) { @@ -348,7 +348,7 @@ public function validateForm(array &$form, array &$form_state) { } else { // File upload failed. - form_set_error('favicon_upload', t('The favicon could not be uploaded.')); + form_set_error('favicon_upload', $form_state, t('The favicon could not be uploaded.')); } } @@ -357,13 +357,13 @@ public function validateForm(array &$form, array &$form_state) { if ($form_state['values']['logo_path']) { $path = $this->validatePath($form_state['values']['logo_path']); if (!$path) { - form_set_error('logo_path', t('The custom logo path is invalid.')); + form_set_error('logo_path', $form_state, t('The custom logo path is invalid.')); } } if ($form_state['values']['favicon_path']) { $path = $this->validatePath($form_state['values']['favicon_path']); if (!$path) { - form_set_error('favicon_path', t('The custom favicon path is invalid.')); + form_set_error('favicon_path', $form_state, t('The custom favicon path is invalid.')); } } } diff --git a/core/modules/system/lib/Drupal/system/Tests/Form/ElementsTableSelectTest.php b/core/modules/system/lib/Drupal/system/Tests/Form/ElementsTableSelectTest.php index 0936151..b8df0f1 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Form/ElementsTableSelectTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Form/ElementsTableSelectTest.php @@ -224,11 +224,11 @@ private function formSubmitHelper($form, $edit) { drupal_process_form($form_id, $form, $form_state); - $errors = form_get_errors(); + $errors = form_get_errors($form_state); // Clear errors and messages. drupal_get_messages(); - form_clear_error(); + $form_state['errors'] = array(); // Return the processed form together with form_state and errors // to allow the caller lowlevel access to the form. diff --git a/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php b/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php index 4aa8eb8..143e371 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php @@ -103,7 +103,6 @@ function testRequiredFields() { $form_id = $this->randomName(); $form = array(); $form_state = form_state_defaults(); - form_clear_error(); $form['op'] = array('#type' => 'submit', '#value' => t('Submit')); $element = $data['element']['#title']; $form[$element] = $data['element']; @@ -113,7 +112,7 @@ function testRequiredFields() { $form_state['method'] = 'post'; drupal_prepare_form($form_id, $form, $form_state); drupal_process_form($form_id, $form, $form_state); - $errors = form_get_errors(); + $errors = form_get_errors($form_state); // Form elements of type 'radios' throw all sorts of PHP notices // when you try to render them like this, so we ignore those for // testing the required marker. @@ -237,9 +236,6 @@ function testRequiredCheckboxesRadio() { * @see form_test_validate_required_form_no_title() */ function testRequiredTextfieldNoTitle() { - $form = $form_state = array(); - form_test_validate_required_form_no_title($form, $form_state); - // Attempt to submit the form with no required field set. $edit = array(); $this->drupalPostForm('form-test/validate-required-no-title', $edit, 'Submit'); diff --git a/core/modules/system/lib/Drupal/system/Tests/Form/ProgrammaticTest.php b/core/modules/system/lib/Drupal/system/Tests/Form/ProgrammaticTest.php index 553abdb..6753239 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Form/ProgrammaticTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Form/ProgrammaticTest.php @@ -81,7 +81,7 @@ private function submitForm($values, $valid_input) { drupal_form_submit('form_test_programmatic_form', $form_state); // Check that the form returns an error when expected, and vice versa. - $errors = form_get_errors(); + $errors = form_get_errors($form_state); $valid_form = empty($errors); $args = array( '%values' => print_r($values, TRUE), diff --git a/core/modules/system/lib/Drupal/system/Tests/System/SystemConfigFormTestBase.php b/core/modules/system/lib/Drupal/system/Tests/System/SystemConfigFormTestBase.php index 5019d86..b923daf 100644 --- a/core/modules/system/lib/Drupal/system/Tests/System/SystemConfigFormTestBase.php +++ b/core/modules/system/lib/Drupal/system/Tests/System/SystemConfigFormTestBase.php @@ -54,7 +54,7 @@ public function testConfigForm() { drupal_form_submit($this->form, $form_state); // Check that the form returns an error when expected, and vice versa. - $errors = form_get_errors(); + $errors = form_get_errors($form_state); $valid_form = empty($errors); $args = array( '%values' => print_r($values, TRUE), diff --git a/core/modules/system/system.module b/core/modules/system/system.module index 71f2860..b30cf8d 100644 --- a/core/modules/system/system.module +++ b/core/modules/system/system.module @@ -2246,13 +2246,13 @@ function system_check_directory($form_element) { if (!is_dir($directory) && !drupal_mkdir($directory, NULL, TRUE)) { // If the directory does not exists and cannot be created. - form_set_error($form_element['#parents'][0], t('The directory %directory does not exist and could not be created.', array('%directory' => $directory))); + form_set_error($form_element['#parents'][0], $form_state, t('The directory %directory does not exist and could not be created.', array('%directory' => $directory))); watchdog('file system', 'The directory %directory does not exist and could not be created.', array('%directory' => $directory), WATCHDOG_ERROR); } if (is_dir($directory) && !is_writable($directory) && !drupal_chmod($directory)) { // If the directory is not writable and cannot be made so. - form_set_error($form_element['#parents'][0], t('The directory %directory exists but is not writable and could not be made writable.', array('%directory' => $directory))); + form_set_error($form_element['#parents'][0], $form_state, t('The directory %directory exists but is not writable and could not be made writable.', array('%directory' => $directory))); watchdog('file system', 'The directory %directory exists but is not writable and could not be made writable.', array('%directory' => $directory), WATCHDOG_ERROR); } elseif (is_dir($directory)) { diff --git a/core/modules/system/tests/modules/form_test/form_test.module b/core/modules/system/tests/modules/form_test/form_test.module index 6c77151..bcd8483 100644 --- a/core/modules/system/tests/modules/form_test/form_test.module +++ b/core/modules/system/tests/modules/form_test/form_test.module @@ -129,7 +129,7 @@ function form_test_validate_form_validate(&$form, &$form_state) { drupal_set_message(t('@label value: @value', array('@label' => $form['name']['#title'], '@value' => $form_state['values']['name']))); // Trigger a form validation error to see our changes. - form_set_error(''); + form_set_error('', $form_state); } } @@ -192,7 +192,7 @@ function form_test_validate_required_form($form, &$form_state) { function form_test_validate_required_form_element_validate($element, &$form_state) { // Set a custom validation error on the #required element. if (!empty($element['#required_but_empty']) && isset($element['#form_test_required_error'])) { - form_error($element, $element['#form_test_required_error']); + form_error($element, $form_state, $element['#form_test_required_error']); } } @@ -295,7 +295,7 @@ function form_test_limit_validation_errors_form($form, &$form_state) { */ function form_test_limit_validation_errors_element_validate_test(&$element, &$form_state) { if ($element['#value'] == 'invalid') { - form_error($element, t('@label element is invalid', array('@label' => $element['#title']))); + form_error($element, $form_state, t('@label element is invalid', array('@label' => $element['#title']))); } } @@ -1830,7 +1830,7 @@ function form_test_programmatic_form($form, &$form_state) { */ function form_test_programmatic_form_validate($form, &$form_state) { if (empty($form_state['values']['textfield'])) { - form_set_error('textfield', t('Textfield is required.')); + form_set_error('textfield', $form_state, t('Textfield is required.')); } } diff --git a/core/modules/system/tests/modules/form_test/lib/Drupal/form_test/Callbacks.php b/core/modules/system/tests/modules/form_test/lib/Drupal/form_test/Callbacks.php index d9b0fe7..08d970d 100644 --- a/core/modules/system/tests/modules/form_test/lib/Drupal/form_test/Callbacks.php +++ b/core/modules/system/tests/modules/form_test/lib/Drupal/form_test/Callbacks.php @@ -44,7 +44,7 @@ public function validateName(&$element, &$form_state) { drupal_set_message(t('@label value: @value', array('@label' => $element['#title'], '@value' => $form_state['values']['name']))); // Trigger a form validation error to see our changes. - form_set_error(''); + form_set_error('', $form_state); } } diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Form/OverviewTerms.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Form/OverviewTerms.php index b85d3fb..20858b9 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Form/OverviewTerms.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Form/OverviewTerms.php @@ -186,7 +186,7 @@ public function buildForm(array $form, array &$form_state, VocabularyInterface $ } } - $errors = form_get_errors() != FALSE ? form_get_errors() : array(); + $errors = form_get_errors($form_state); $destination = drupal_get_destination(); $row_position = 0; // Build the actual form. diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/views/filter/TaxonomyIndexTid.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/views/filter/TaxonomyIndexTid.php index 486ae5f..f421904 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/views/filter/TaxonomyIndexTid.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/views/filter/TaxonomyIndexTid.php @@ -323,7 +323,7 @@ function validate_term_strings(&$form, $values) { } if ($missing && !empty($this->options['error_message'])) { - form_error($form, format_plural(count($missing), 'Unable to find term: @terms', 'Unable to find terms: @terms', array('@terms' => implode(', ', array_keys($missing))))); + form_error($form, $form_state, format_plural(count($missing), 'Unable to find term: @terms', 'Unable to find terms: @terms', array('@terms' => implode(', ', array_keys($missing))))); } elseif ($missing && empty($this->options['error_message'])) { $tids = array(0); diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/TermFormController.php b/core/modules/taxonomy/lib/Drupal/taxonomy/TermFormController.php index c6692aa..e7fb41e 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/TermFormController.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/TermFormController.php @@ -161,7 +161,7 @@ public function validate(array $form, array &$form_state) { // Ensure numeric values. if (isset($form_state['values']['weight']) && !is_numeric($form_state['values']['weight'])) { - form_set_error('weight', $this->t('Weight value must be numeric.')); + form_set_error('weight', $form_state, $this->t('Weight value must be numeric.')); } } diff --git a/core/modules/update/lib/Drupal/update/UpdateSettingsForm.php b/core/modules/update/lib/Drupal/update/UpdateSettingsForm.php index 580b331..f72c201 100644 --- a/core/modules/update/lib/Drupal/update/UpdateSettingsForm.php +++ b/core/modules/update/lib/Drupal/update/UpdateSettingsForm.php @@ -90,10 +90,10 @@ public function validateForm(array &$form, array &$form_state) { $form_state['notify_emails'] = $valid; } elseif (count($invalid) == 1) { - form_set_error('update_notify_emails', t('%email is not a valid e-mail address.', array('%email' => reset($invalid)))); + form_set_error('update_notify_emails', $form_state, t('%email is not a valid e-mail address.', array('%email' => reset($invalid)))); } else { - form_set_error('update_notify_emails', t('%emails are not valid e-mail addresses.', array('%emails' => implode(', ', $invalid)))); + form_set_error('update_notify_emails', $form_state, t('%emails are not valid e-mail addresses.', array('%emails' => implode(', ', $invalid)))); } } diff --git a/core/modules/update/update.manager.inc b/core/modules/update/update.manager.inc index 6063dfc..e411c2f 100644 --- a/core/modules/update/update.manager.inc +++ b/core/modules/update/update.manager.inc @@ -314,7 +314,7 @@ function update_manager_update_form_validate($form, &$form_state) { $disabled = array_filter($form_state['values']['disabled_projects']); } if (empty($enabled) && empty($disabled)) { - form_set_error('projects', t('You must select at least one project to update.')); + form_set_error('projects', $form_state, t('You must select at least one project to update.')); } } @@ -633,7 +633,7 @@ function _update_manager_check_backends(&$form, $operation) { */ function update_manager_install_form_validate($form, &$form_state) { if (!($form_state['values']['project_url'] XOR !empty($_FILES['files']['name']['project_upload']))) { - form_set_error('project_url', t('You must either provide a URL or upload an archive file to install.')); + form_set_error('project_url', $form_state, t('You must either provide a URL or upload an archive file to install.')); } } @@ -658,14 +658,14 @@ function update_manager_install_form_submit($form, &$form_state) { $field = 'project_url'; $local_cache = update_manager_file_get($form_state['values']['project_url']); if (!$local_cache) { - form_set_error($field, t('Unable to retrieve Drupal project from %url.', array('%url' => $form_state['values']['project_url']))); + form_set_error($field, $form_state, t('Unable to retrieve Drupal project from %url.', array('%url' => $form_state['values']['project_url']))); return; } } elseif ($_FILES['files']['name']['project_upload']) { $validators = array('file_validate_extensions' => array(archiver_get_extensions())); $field = 'project_upload'; - if (!($finfo = file_save_upload($field, $validators, NULL, 0, FILE_EXISTS_REPLACE))) { + if (!($finfo = file_save_upload($field, $form_state, $validators, NULL, 0, FILE_EXISTS_REPLACE))) { // Failed to upload the file. file_save_upload() calls form_set_error() on // failure. return; @@ -678,13 +678,13 @@ function update_manager_install_form_submit($form, &$form_state) { $archive = update_manager_archive_extract($local_cache, $directory); } catch (Exception $e) { - form_set_error($field, $e->getMessage()); + form_set_error($field, $form_state, $e->getMessage()); return; } $files = $archive->listContents(); if (!$files) { - form_set_error($field, t('Provided archive contains no files.')); + form_set_error($field, $form_state, t('Provided archive contains no files.')); return; } @@ -695,7 +695,7 @@ function update_manager_install_form_submit($form, &$form_state) { $archive_errors = update_manager_archive_verify($project, $local_cache, $directory); if (!empty($archive_errors)) { - form_set_error($field, array_shift($archive_errors)); + form_set_error($field, $form_state, array_shift($archive_errors)); // @todo: Fix me in D8: We need a way to set multiple errors on the same // form element and have all of them appear! if (!empty($archive_errors)) { @@ -714,7 +714,7 @@ function update_manager_install_form_submit($form, &$form_state) { $updater = Updater::factory($project_location); } catch (Exception $e) { - form_set_error($field, $e->getMessage()); + form_set_error($field, $form_state, $e->getMessage()); return; } @@ -722,16 +722,16 @@ function update_manager_install_form_submit($form, &$form_state) { $project_title = Updater::getProjectTitle($project_location); } catch (Exception $e) { - form_set_error($field, $e->getMessage()); + form_set_error($field, $form_state, $e->getMessage()); return; } if (!$project_title) { - form_set_error($field, t('Unable to determine %project name.', array('%project' => $project))); + form_set_error($field, $form_state, t('Unable to determine %project name.', array('%project' => $project))); } if ($updater->isInstalled()) { - form_set_error($field, t('%project is already installed.', array('%project' => $project_title))); + form_set_error($field, $form_state, t('%project is already installed.', array('%project' => $project_title))); return; } diff --git a/core/modules/user/lib/Drupal/user/AccountFormController.php b/core/modules/user/lib/Drupal/user/AccountFormController.php index fdb39ae..1179cdc 100644 --- a/core/modules/user/lib/Drupal/user/AccountFormController.php +++ b/core/modules/user/lib/Drupal/user/AccountFormController.php @@ -296,7 +296,7 @@ public function validate(array $form, array &$form_state) { // Validate new or changing username. if (isset($form_state['values']['name'])) { if ($error = user_validate_name($form_state['values']['name'])) { - form_set_error('name', $error); + form_set_error('name', $form_state, $error); } // Cast the user ID as an integer. It might have been set to NULL, which // could lead to unexpected results. @@ -310,7 +310,7 @@ public function validate(array $form, array &$form_state) { ->fetchField(); if ($name_taken) { - form_set_error('name', $this->t('The name %name is already taken.', array('%name' => $form_state['values']['name']))); + form_set_error('name', $form_state, $this->t('The name %name is already taken.', array('%name' => $form_state['values']['name']))); } } } @@ -329,10 +329,10 @@ public function validate(array $form, array &$form_state) { if ($mail_taken) { // Format error message dependent on whether the user is logged in or not. if ($GLOBALS['user']->isAuthenticated()) { - form_set_error('mail', $this->t('The e-mail address %email is already taken.', array('%email' => $mail))); + form_set_error('mail', $form_state, $this->t('The e-mail address %email is already taken.', array('%email' => $mail))); } else { - form_set_error('mail', $this->t('The e-mail address %email is already registered. Have you forgotten your password?', array('%email' => $mail, '@password' => url('user/password')))); + form_set_error('mail', $form_state, $this->t('The e-mail address %email is already registered. Have you forgotten your password?', array('%email' => $mail, '@password' => url('user/password')))); } } } @@ -347,7 +347,7 @@ public function validate(array $form, array &$form_state) { $user_schema = drupal_get_schema('users'); if (drupal_strlen($form_state['values']['signature']) > $user_schema['fields']['signature']['length']) { - form_set_error('signature', $this->t('The signature is too long: it must be %max characters or less.', array('%max' => $user_schema['fields']['signature']['length']))); + form_set_error('signature', $form_state, $this->t('The signature is too long: it must be %max characters or less.', array('%max' => $user_schema['fields']['signature']['length']))); } } } diff --git a/core/modules/user/lib/Drupal/user/Form/UserLoginForm.php b/core/modules/user/lib/Drupal/user/Form/UserLoginForm.php index aa0228d..4aad0e9 100644 --- a/core/modules/user/lib/Drupal/user/Form/UserLoginForm.php +++ b/core/modules/user/lib/Drupal/user/Form/UserLoginForm.php @@ -118,7 +118,7 @@ public function submitForm(array &$form, array &$form_state) { public function validateName(array &$form, array &$form_state) { if (!empty($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) { // Blocked in user administration. - form_set_error('name', $this->t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name']))); + form_set_error('name', $form_state, $this->t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name']))); } } @@ -186,15 +186,15 @@ public function validateFinal(array &$form, array &$form_state) { if (isset($form_state['flood_control_triggered'])) { if ($form_state['flood_control_triggered'] == 'user') { - form_set_error('name', format_plural($flood_config->get('user_limit'), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or request a new password.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or request a new password.', array('@url' => url('user/password')))); + form_set_error('name', $form_state, format_plural($flood_config->get('user_limit'), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or request a new password.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or request a new password.', array('@url' => url('user/password')))); } else { // We did not find a uid, so the limit is IP-based. - form_set_error('name', $this->t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or request a new password.', array('@url' => url('user/password')))); + form_set_error('name', $form_state, $this->t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or request a new password.', array('@url' => url('user/password')))); } } else { - form_set_error('name', $this->t('Sorry, unrecognized username or password. Have you forgotten your password?', array('@password' => url('user/password', array('query' => array('name' => $form_state['values']['name'])))))); + form_set_error('name', $form_state, $this->t('Sorry, unrecognized username or password. Have you forgotten your password?', array('@password' => url('user/password', array('query' => array('name' => $form_state['values']['name'])))))); $accounts = $this->userStorage->loadByProperties(array('name' => $form_state['values']['name'])); if (!empty($accounts)) { watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name'])); diff --git a/core/modules/user/lib/Drupal/user/Form/UserPasswordForm.php b/core/modules/user/lib/Drupal/user/Form/UserPasswordForm.php index af22943..2399a58 100644 --- a/core/modules/user/lib/Drupal/user/Form/UserPasswordForm.php +++ b/core/modules/user/lib/Drupal/user/Form/UserPasswordForm.php @@ -119,7 +119,7 @@ public function validateForm(array &$form, array &$form_state) { form_set_value(array('#parents' => array('account')), $account, $form_state); } else { - form_set_error('name', $this->t('Sorry, %name is not recognized as a username or an e-mail address.', array('%name' => $name))); + form_set_error('name', $form_state, $this->t('Sorry, %name is not recognized as a username or an e-mail address.', array('%name' => $name))); } } diff --git a/core/modules/user/lib/Drupal/user/Plugin/views/access/Role.php b/core/modules/user/lib/Drupal/user/Plugin/views/access/Role.php index 1bac7f1..d812270 100644 --- a/core/modules/user/lib/Drupal/user/Plugin/views/access/Role.php +++ b/core/modules/user/lib/Drupal/user/Plugin/views/access/Role.php @@ -81,7 +81,7 @@ public function buildOptionsForm(&$form, &$form_state) { public function validateOptionsForm(&$form, &$form_state) { if (!array_filter($form_state['values']['access_options']['role'])) { - form_error($form['role'], t('You must select at least one role if type is "by role"')); + form_error($form['role'], $form_state, t('You must select at least one role if type is "by role"')); } } diff --git a/core/modules/user/lib/Drupal/user/Plugin/views/field/UserBulkForm.php b/core/modules/user/lib/Drupal/user/Plugin/views/field/UserBulkForm.php index 4af7b6f..5aac698 100644 --- a/core/modules/user/lib/Drupal/user/Plugin/views/field/UserBulkForm.php +++ b/core/modules/user/lib/Drupal/user/Plugin/views/field/UserBulkForm.php @@ -57,7 +57,7 @@ public function views_form(&$form, &$form_state) { public function views_form_validate(&$form, &$form_state) { $selected = array_filter($form_state['values'][$this->options['id']]); if (empty($selected)) { - form_set_error('', t('No users selected.')); + form_set_error('', $form_state, t('No users selected.')); } } diff --git a/core/modules/user/lib/Drupal/user/Plugin/views/filter/Name.php b/core/modules/user/lib/Drupal/user/Plugin/views/filter/Name.php index ed20d4e..d033e72 100644 --- a/core/modules/user/lib/Drupal/user/Plugin/views/filter/Name.php +++ b/core/modules/user/lib/Drupal/user/Plugin/views/filter/Name.php @@ -52,7 +52,7 @@ protected function valueForm(&$form, &$form_state) { protected function valueValidate($form, &$form_state) { $values = drupal_explode_tags($form_state['values']['options']['value']); - $uids = $this->validate_user_strings($form['value'], $values); + $uids = $this->validate_user_strings($form['value'], $form_state, $values); if ($uids) { $form_state['values']['options']['value'] = $uids; @@ -92,7 +92,7 @@ public function validateExposed(&$form, &$form_state) { $values = drupal_explode_tags($input); if (!$this->options['is_grouped'] || ($this->options['is_grouped'] && ($input != 'All'))) { - $uids = $this->validate_user_strings($form[$identifier], $values); + $uids = $this->validate_user_strings($form[$identifier], $form_state, $values); } else { $uids = FALSE; @@ -108,7 +108,7 @@ public function validateExposed(&$form, &$form_state) { * or the exposed filter, this is abstracted out a bit so it can * handle the multiple input sources. */ - function validate_user_strings(&$form, $values) { + function validate_user_strings(&$form, array &$form_state, $values) { $uids = array(); $placeholders = array(); $args = array(); @@ -134,7 +134,7 @@ function validate_user_strings(&$form, $values) { } if ($missing) { - form_error($form, format_plural(count($missing), 'Unable to find user: @users', 'Unable to find users: @users', array('@users' => implode(', ', array_keys($missing))))); + form_error($form, $form_state, format_plural(count($missing), 'Unable to find user: @users', 'Unable to find users: @users', array('@users' => implode(', ', array_keys($missing))))); } return $uids; diff --git a/core/modules/user/user.module b/core/modules/user/user.module index 742727d..2be87e9 100644 --- a/core/modules/user/user.module +++ b/core/modules/user/user.module @@ -550,8 +550,8 @@ function user_validate_current_pass(&$form, &$form_state) { if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $current_value)) { $current_pass_failed = empty($form_state['values']['current_pass']) || !\Drupal::service('password')->check($form_state['values']['current_pass'], $account); if ($current_pass_failed) { - form_set_error('current_pass', t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name))); - form_set_error($key); + form_set_error('current_pass', $form_state, t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name))); + form_set_error($key, $form_state); } // We only need to check the password once. break; @@ -611,7 +611,7 @@ function user_template_preprocess_default_variables_alter(&$variables) { } $variables['user'] = clone $user; - // Remove password and session IDs, since themes should not need nor see them. + // Remove password and session IDs, $form_state, since themes should not need nor see them. unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid); $variables['is_admin'] = user_access('access administration pages'); diff --git a/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php b/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php index 9b63cb7..1fd8db8 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php +++ b/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php @@ -222,7 +222,7 @@ public function settingsFormValidate($element, &$form_state, $form) { list($view, $display) = explode(':', $element['view_and_display']['#value']); } else { - form_error($element, t('The views entity selection mode requires a view.')); + form_error($element, $form_state, t('The views entity selection mode requires a view.')); return; } diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/cache/Time.php b/core/modules/views/lib/Drupal/views/Plugin/views/cache/Time.php index 18b25c8..05dcefc 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/cache/Time.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/cache/Time.php @@ -91,7 +91,7 @@ public function validateOptionsForm(&$form, &$form_state) { $custom_fields = array('output_lifespan', 'results_lifespan'); foreach ($custom_fields as $field) { if ($form_state['values']['cache_options'][$field] == 'custom' && !is_numeric($form_state['values']['cache_options'][$field . '_custom'])) { - form_error($form[$field .'_custom'], t('Custom time values must be numeric.')); + form_error($form[$field .'_custom'], $form_state, t('Custom time values must be numeric.')); } } } diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/display/DisplayPluginBase.php b/core/modules/views/lib/Drupal/views/Plugin/views/display/DisplayPluginBase.php index 7af12f7..533faaa 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/display/DisplayPluginBase.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/display/DisplayPluginBase.php @@ -2098,24 +2098,24 @@ public function validateOptionsForm(&$form, &$form_state) { switch ($form_state['section']) { case 'display_title': if (empty($form_state['values']['display_title'])) { - form_error($form['display_title'], t('Display title may not be empty.')); + form_error($form['display_title'], $form_state, t('Display title may not be empty.')); } break; case 'css_class': $css_class = $form_state['values']['css_class']; if (preg_match('/[^a-zA-Z0-9-_ ]/', $css_class)) { - form_error($form['css_class'], t('CSS classes must be alphanumeric or dashes only.')); + form_error($form['css_class'], $form_state, t('CSS classes must be alphanumeric or dashes only.')); } break; case 'display_id': if ($form_state['values']['display_id']) { if (preg_match('/[^a-z0-9_]/', $form_state['values']['display_id'])) { - form_error($form['display_id'], t('Display name must be letters, numbers, or underscores only.')); + form_error($form['display_id'], $form_state, t('Display name must be letters, numbers, or underscores only.')); } foreach ($this->view->display as $id => $display) { if ($id != $this->view->current_display && ($form_state['values']['display_id'] == $id || (isset($display->new_id) && $form_state['values']['display_id'] == $display->new_id))) { - form_error($form['display_id'], t('Display id should be unique.')); + form_error($form['display_id'], $form_state, t('Display id should be unique.')); } } } diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/display/Page.php b/core/modules/views/lib/Drupal/views/Plugin/views/display/Page.php index 75758e7..a289c21 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/display/Page.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/display/Page.php @@ -375,19 +375,19 @@ public function validateOptionsForm(&$form, &$form_state) { if ($form_state['section'] == 'menu') { $path = $this->getOption('path'); if ($form_state['values']['menu']['type'] == 'normal' && strpos($path, '%') !== FALSE) { - form_error($form['menu']['type'], t('Views cannot create normal menu items for paths with a % in them.')); + form_error($form['menu']['type'], $form_state, t('Views cannot create normal menu items for paths with a % in them.')); } if ($form_state['values']['menu']['type'] == 'default tab' || $form_state['values']['menu']['type'] == 'tab') { $bits = explode('/', $path); $last = array_pop($bits); if ($last == '%') { - form_error($form['menu']['type'], t('A display whose path ends with a % cannot be a tab.')); + form_error($form['menu']['type'], $form_state, t('A display whose path ends with a % cannot be a tab.')); } } if ($form_state['values']['menu']['type'] != 'none' && empty($form_state['values']['menu']['title'])) { - form_error($form['menu']['title'], t('Title is required for this menu type.')); + form_error($form['menu']['title'], $form_state, t('Title is required for this menu type.')); } } } diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/display/PathPluginBase.php b/core/modules/views/lib/Drupal/views/Plugin/views/display/PathPluginBase.php index ac3cb9e..feeb717 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/display/PathPluginBase.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/display/PathPluginBase.php @@ -430,7 +430,7 @@ public function validateOptionsForm(&$form, &$form_state) { if ($form_state['section'] == 'path') { if (strpos($form_state['values']['path'], '%') === 0) { - form_error($form['path'], t('"%" may not be used for the first segment of a path.')); + form_error($form['path'], $form_state, t('"%" may not be used for the first segment of a path.')); } // Automatically remove '/' and trailing whitespace from path. diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/field/Serialized.php b/core/modules/views/lib/Drupal/views/Plugin/views/field/Serialized.php index 2ec3756..db67c57 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/field/Serialized.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/field/Serialized.php @@ -56,7 +56,7 @@ public function buildOptionsForm(&$form, &$form_state) { public function validateOptionsForm(&$form, &$form_state) { // Require a key if the format is key. if ($form_state['values']['options']['format'] == 'key' && $form_state['values']['options']['key'] == '') { - form_error($form['key'], t('You have to enter a key if you want to display a key of the data.')); + form_error($form['key'], $form_state, t('You have to enter a key if you want to display a key of the data.')); } } diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/filter/BooleanOperator.php b/core/modules/views/lib/Drupal/views/Plugin/views/filter/BooleanOperator.php index 045edd5..0d787a8 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/filter/BooleanOperator.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/filter/BooleanOperator.php @@ -165,7 +165,7 @@ protected function valueForm(&$form, &$form_state) { protected function valueValidate($form, &$form_state) { if (isset($form_state['values']['options']['value']) && $form_state['values']['options']['value'] == 'All' && !empty($form_state['values']['options']['expose']['required'])) { - form_set_error('value', t('You must select a value unless this is an non-required exposed filter.')); + form_set_error('value', $form_state, t('You must select a value unless this is an non-required exposed filter.')); } } diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/filter/Combine.php b/core/modules/views/lib/Drupal/views/Plugin/views/filter/Combine.php index 529dee5..ceafdb8 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/filter/Combine.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/filter/Combine.php @@ -51,7 +51,7 @@ public function buildOptionsForm(&$form, &$form_state) { ); } else { - form_set_error('', t('You have to add some fields to be able to use this filter.')); + form_set_error('', $form_state, t('You have to add some fields to be able to use this filter.')); } } } diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/filter/Date.php b/core/modules/views/lib/Drupal/views/Plugin/views/filter/Date.php index 19f1b12..2d6b0d3 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/filter/Date.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/filter/Date.php @@ -53,7 +53,7 @@ public function validateOptionsForm(&$form, &$form_state) { return; } - $this->validateValidTime($form['value'], $form_state['values']['options']['operator'], $form_state['values']['options']['value']); + $this->validateValidTime($form['value'], $form_state, $form_state['values']['options']['operator'], $form_state['values']['options']['value']); } public function validateExposed(&$form, &$form_state) { @@ -74,30 +74,30 @@ public function validateExposed(&$form, &$form_state) { $operator = $this->operator; } - $this->validateValidTime($this->options['expose']['identifier'], $operator, $value); + $this->validateValidTime($this->options['expose']['identifier'], $form_state, $operator, $value); } /** * Validate that the time values convert to something usable. */ - public function validateValidTime(&$form, $operator, $value) { + public function validateValidTime(&$form, array &$form_state, $operator, $value) { $operators = $this->operators(); if ($operators[$operator]['values'] == 1) { $convert = strtotime($value['value']); if (!empty($form['value']) && ($convert == -1 || $convert === FALSE)) { - form_error($form['value'], t('Invalid date format.')); + form_error($form['value'], $form_state, t('Invalid date format.')); } } elseif ($operators[$operator]['values'] == 2) { $min = strtotime($value['min']); if ($min == -1 || $min === FALSE) { - form_error($form['min'], t('Invalid date format.')); + form_error($form['min'], $form_state, t('Invalid date format.')); } $max = strtotime($value['max']); if ($max == -1 || $max === FALSE) { - form_error($form['max'], t('Invalid date format.')); + form_error($form['max'], $form_state, t('Invalid date format.')); } } } @@ -115,14 +115,14 @@ protected function buildGroupValidate($form, &$form_state) { // Check if the title is defined but value wasn't defined. if (!empty($group['title'])) { if ((!is_array($group['value']) && empty($group['value'])) || (is_array($group['value']) && count(array_filter($group['value'])) == 1)) { - form_error($form['group_info']['group_items'][$id]['value'], t('The value is required if title for this item is defined.')); + form_error($form['group_info']['group_items'][$id]['value'], $form_state, t('The value is required if title for this item is defined.')); } } // Check if the value is defined but title wasn't defined. if ((!is_array($group['value']) && !empty($group['value'])) || (is_array($group['value']) && count(array_filter($group['value'])) > 1)) { if (empty($group['title'])) { - form_error($form['group_info']['group_items'][$id]['title'], t('The title is required if value for this item is defined.')); + form_error($form['group_info']['group_items'][$id]['title'], $form_state, t('The title is required if value for this item is defined.')); } } } diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/filter/FilterPluginBase.php b/core/modules/views/lib/Drupal/views/Plugin/views/filter/FilterPluginBase.php index ba2adde..bf60686 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/filter/FilterPluginBase.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/filter/FilterPluginBase.php @@ -603,15 +603,15 @@ public function buildExposeForm(&$form, &$form_state) { */ public function validateExposeForm($form, &$form_state) { if (empty($form_state['values']['options']['expose']['identifier'])) { - form_error($form['expose']['identifier'], t('The identifier is required if the filter is exposed.')); + form_error($form['expose']['identifier'], $form_state, t('The identifier is required if the filter is exposed.')); } if (!empty($form_state['values']['options']['expose']['identifier']) && $form_state['values']['options']['expose']['identifier'] == 'value') { - form_error($form['expose']['identifier'], t('This identifier is not allowed.')); + form_error($form['expose']['identifier'], $form_state, t('This identifier is not allowed.')); } if (!$this->view->display_handler->isIdentifierUnique($form_state['id'], $form_state['values']['options']['expose']['identifier'])) { - form_error($form['expose']['identifier'], t('This identifier is used by another handler.')); + form_error($form['expose']['identifier'], $form_state, t('This identifier is used by another handler.')); } } @@ -621,15 +621,15 @@ public function validateExposeForm($form, &$form_state) { protected function buildGroupValidate($form, &$form_state) { if (!empty($form_state['values']['options']['group_info'])) { if (empty($form_state['values']['options']['group_info']['identifier'])) { - form_error($form['group_info']['identifier'], t('The identifier is required if the filter is exposed.')); + form_error($form['group_info']['identifier'], $form_state, t('The identifier is required if the filter is exposed.')); } if (!empty($form_state['values']['options']['group_info']['identifier']) && $form_state['values']['options']['group_info']['identifier'] == 'value') { - form_error($form['group_info']['identifier'], t('This identifier is not allowed.')); + form_error($form['group_info']['identifier'], $form_state, t('This identifier is not allowed.')); } if (!$this->view->display_handler->isIdentifierUnique($form_state['id'], $form_state['values']['options']['group_info']['identifier'])) { - form_error($form['group_info']['identifier'], t('This identifier is used by another handler.')); + form_error($form['group_info']['identifier'], $form_state, t('This identifier is used by another handler.')); } } @@ -643,7 +643,7 @@ protected function buildGroupValidate($form, &$form_state) { if (!empty($group['title']) && $operators[$group['operator']]['values'] > 0) { if ((!is_array($group['value']) && trim($group['value']) == "") || (is_array($group['value']) && count(array_filter($group['value'], 'static::arrayFilterZero')) == 0)) { - form_error($form['group_info']['group_items'][$id]['value'], + form_error($form['group_info']['group_items'][$id]['value'], $form_state, t('The value is required if title for this item is defined.')); } } @@ -652,7 +652,7 @@ protected function buildGroupValidate($form, &$form_state) { if ((!is_array($group['value']) && trim($group['value']) != "") || (is_array($group['value']) && count(array_filter($group['value'], 'static::arrayFilterZero')) > 0)) { if (empty($group['title'])) { - form_error($form['group_info']['group_items'][$id]['title'], + form_error($form['group_info']['group_items'][$id]['title'], $form_state, t('The title is required if value for this item is defined.')); } } diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/pager/SqlBase.php b/core/modules/views/lib/Drupal/views/Plugin/views/pager/SqlBase.php index 1e6ab81..3908936 100644 --- a/core/modules/views/lib/Drupal/views/Plugin/views/pager/SqlBase.php +++ b/core/modules/views/lib/Drupal/views/Plugin/views/pager/SqlBase.php @@ -195,14 +195,14 @@ public function validateOptionsForm(&$form, &$form_state) { $error = TRUE; } if ($error) { - form_set_error('pager_options][expose][items_per_page_options', t('Insert a list of integer numeric values separated by commas: e.g: 10, 20, 50, 100')); + form_set_error('pager_options][expose][items_per_page_options', $form_state, t('Insert a list of integer numeric values separated by commas: e.g: 10, 20, 50, 100')); } // Take sure that the items_per_page is part of the expose settings. if (!empty($form_state['values']['pager_options']['expose']['items_per_page']) && !empty($form_state['values']['pager_options']['items_per_page'])) { $items_per_page = $form_state['values']['pager_options']['items_per_page']; if (array_search($items_per_page, $options) === FALSE) { - form_set_error('pager_options][expose][items_per_page_options', t('Insert the items per page (@items_per_page) from above.', + form_set_error('pager_options][expose][items_per_page_options', $form_state, t('Insert the items per page (@items_per_page) from above.', array('@items_per_page' => $items_per_page)) ); } @@ -369,7 +369,7 @@ public function exposedFormAlter(&$form, &$form_state) { public function exposedFormValidate(&$form, &$form_state) { if (!empty($form_state['values']['offset']) && trim($form_state['values']['offset'])) { if (!is_numeric($form_state['values']['offset']) || $form_state['values']['offset'] < 0) { - form_set_error('offset', t('Offset must be an number greather or equal than 0.')); + form_set_error('offset', $form_state, t('Offset must be an number greather or equal than 0.')); } } } diff --git a/core/modules/views/lib/Drupal/views/ViewExecutable.php b/core/modules/views/lib/Drupal/views/ViewExecutable.php index 435da78..4207b6b 100644 --- a/core/modules/views/lib/Drupal/views/ViewExecutable.php +++ b/core/modules/views/lib/Drupal/views/ViewExecutable.php @@ -1081,9 +1081,9 @@ public function build($display_id = NULL) { if ($this->display_handler->usesExposed()) { $exposed_form = $this->display_handler->getPlugin('exposed_form'); $this->exposed_widgets = $exposed_form->renderExposedForm(); - if (form_set_error() || !empty($this->build_info['abort'])) { + if (\Drupal::formBuilder()->getAnyErrors() || !empty($this->build_info['abort'])) { $this->built = TRUE; - // Don't execute the query, but rendering will still be executed to display the empty text. + // Don't execute the query, $form_state, but rendering will still be executed to display the empty text. $this->executed = TRUE; return empty($this->build_info['fail']); } diff --git a/core/modules/views/tests/modules/views_test_data/lib/Drupal/views_test_data/Plugin/views/display/DisplayTest.php b/core/modules/views/tests/modules/views_test_data/lib/Drupal/views_test_data/Plugin/views/display/DisplayTest.php index e8ffa64..aaa9e0f 100644 --- a/core/modules/views/tests/modules/views_test_data/lib/Drupal/views_test_data/Plugin/views/display/DisplayTest.php +++ b/core/modules/views/tests/modules/views_test_data/lib/Drupal/views_test_data/Plugin/views/display/DisplayTest.php @@ -100,7 +100,7 @@ public function validateOptionsForm(&$form, &$form_state) { switch ($form_state['section']) { case 'test_option': if (!trim($form_state['values']['test_option'])) { - form_error($form['test_option'], t('You cannot have an empty option.')); + form_error($form['test_option'], $form_state, t('You cannot have an empty option.')); } break; } diff --git a/core/modules/views/views.module b/core/modules/views/views.module index 5bea350..2c2afa8 100644 --- a/core/modules/views/views.module +++ b/core/modules/views/views.module @@ -1350,7 +1350,7 @@ function views_element_validate_tags($element, &$form_state) { $values = array_map('trim', explode(',', $element['#value'])); foreach ($values as $value) { if (preg_match("/[^a-z_]/", $value)) { - form_error($element, t('The query tags may only contain lower-case alphabetical characters and underscores.')); + form_error($element, $form_state, t('The query tags may only contain lower-case alphabetical characters and underscores.')); return; } } diff --git a/core/modules/views_ui/lib/Drupal/views_ui/Form/Ajax/ConfigItem.php b/core/modules/views_ui/lib/Drupal/views_ui/Form/Ajax/ConfigItem.php index 0185bf7..b84ddb2 100644 --- a/core/modules/views_ui/lib/Drupal/views_ui/Form/Ajax/ConfigItem.php +++ b/core/modules/views_ui/lib/Drupal/views_ui/Form/Ajax/ConfigItem.php @@ -192,7 +192,7 @@ public function buildForm(array $form, array &$form_state) { public function validateForm(array &$form, array &$form_state) { $form_state['handler']->validateOptionsForm($form['options'], $form_state); - if (form_get_errors()) { + if (form_get_errors($form_state)) { $form_state['rerender'] = TRUE; } } diff --git a/core/modules/views_ui/lib/Drupal/views_ui/Form/Ajax/Display.php b/core/modules/views_ui/lib/Drupal/views_ui/Form/Ajax/Display.php index 5b85f37..619d6a5 100644 --- a/core/modules/views_ui/lib/Drupal/views_ui/Form/Ajax/Display.php +++ b/core/modules/views_ui/lib/Drupal/views_ui/Form/Ajax/Display.php @@ -99,7 +99,7 @@ public function buildForm(array $form, array &$form_state) { public function validateForm(array &$form, array &$form_state) { $form_state['view']->getExecutable()->displayHandlers->get($form_state['display_id'])->validateOptionsForm($form['options'], $form_state); - if (form_get_errors()) { + if (form_get_errors($form_state)) { $form_state['rerender'] = TRUE; } } diff --git a/core/modules/views_ui/lib/Drupal/views_ui/ViewAddFormController.php b/core/modules/views_ui/lib/Drupal/views_ui/ViewAddFormController.php index 5e65fd94..8ed1745 100644 --- a/core/modules/views_ui/lib/Drupal/views_ui/ViewAddFormController.php +++ b/core/modules/views_ui/lib/Drupal/views_ui/ViewAddFormController.php @@ -180,7 +180,7 @@ public function validate(array $form, array &$form_state) { foreach ($errors as $display_errors) { foreach ($display_errors as $name => $message) { - form_set_error($name, $message); + form_set_error($name, $form_state, $message); } } } diff --git a/core/modules/views_ui/lib/Drupal/views_ui/ViewEditFormController.php b/core/modules/views_ui/lib/Drupal/views_ui/ViewEditFormController.php index 6bb082e..f8fd10a 100644 --- a/core/modules/views_ui/lib/Drupal/views_ui/ViewEditFormController.php +++ b/core/modules/views_ui/lib/Drupal/views_ui/ViewEditFormController.php @@ -236,7 +236,7 @@ public function validate(array $form, array &$form_state) { $view = $this->entity; foreach ($view->getExecutable()->validate() as $display_errors) { foreach ($display_errors as $error) { - form_set_error('', $error); + form_set_error('', $form_state, $error); } } } diff --git a/core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php b/core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php index b0779bd..8e4ed05 100644 --- a/core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php +++ b/core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php @@ -163,10 +163,7 @@ public function testGetFormIdWithInjectedClassName() { public function testGetFormIdWithObject() { $expected_form_id = 'my_module_form_id'; - $form_arg = $this->getMock('Drupal\Core\Form\FormInterface'); - $form_arg->expects($this->once()) - ->method('getFormId') - ->will($this->returnValue($expected_form_id)); + $form_arg = $this->getMockForm($expected_form_id); $form_state = array(); $form_id = $this->formBuilder->getFormId($form_arg, $form_state); @@ -349,14 +346,7 @@ public function testGetFormWithObject() { $form_id = 'test_form_id'; $expected_form = $form_id(); - $form_arg = $this->getMock('Drupal\Core\Form\FormInterface'); - $form_arg->expects($this->once()) - ->method('getFormId') - ->will($this->returnValue($form_id)); - $form_arg->expects($this->once()) - ->method('buildForm') - ->will($this->returnValue($expected_form)); - + $form_arg = $this->getMockForm($form_id, $expected_form); $form = $this->formBuilder->getForm($form_arg); $this->assertFormElement($expected_form, $form, 'test'); @@ -370,10 +360,7 @@ public function testBuildFormWithObject() { $form_id = 'test_form_id'; $expected_form = $form_id(); - $form_arg = $this->getMock('Drupal\Core\Form\FormInterface'); - $form_arg->expects($this->once()) - ->method('buildForm') - ->will($this->returnValue($expected_form)); + $form_arg = $this->getMockForm(NULL, $expected_form); $form_state['build_info']['callback_object'] = $form_arg; $form_state['build_info']['args'] = array(); @@ -392,7 +379,7 @@ public function testBuildFormWithHookForms() { $base_form_id = 'test_form_id'; $expected_form = $base_form_id(); // Set the module handler to return information from hook_forms(). - $this->moduleHandler->expects($this->any()) + $this->moduleHandler->expects($this->once()) ->method('invokeAll') ->with('forms', array($form_id, array())) ->will($this->returnValue(array( @@ -417,10 +404,8 @@ public function testRebuildForm() { $form_id = 'test_form_id'; $expected_form = $form_id(); - $form_arg = $this->getMock('Drupal\Core\Form\FormInterface'); - $form_arg->expects($this->any()) - ->method('buildForm') - ->will($this->returnValue($expected_form)); + // The form will be built four times. + $form_arg = $this->getMockForm(NULL, $expected_form, 4); // Do an initial build of the form and track the build ID. $form_state = array(); @@ -446,39 +431,133 @@ public function testRebuildForm() { * Tests the submitForm() method. */ public function testSubmitForm() { - $expected_form = test_form_id(); + $form_id = 'test_form_id'; + $expected_form = $form_id(); $expected_form['test']['#required'] = TRUE; $expected_form['options']['#required'] = TRUE; $expected_form['value']['#required'] = TRUE; $form_arg = $this->getMock('Drupal\Core\Form\FormInterface'); - $form_arg->expects($this->any()) + $form_arg->expects($this->exactly(3)) + ->method('getFormId') + ->will($this->returnValue($form_id)); + $form_arg->expects($this->exactly(3)) ->method('buildForm') ->will($this->returnValue($expected_form)); $form_state = array(); $form_state['values']['test'] = $this->randomName(); + $form_state['values']['op'] = 'Submit'; $this->formBuilder->submitForm($form_arg, $form_state); - $errors = $this->formBuilder->getErrors(); + $errors = $this->formBuilder->getErrors($form_state); $this->assertNotEmpty($errors['options']); $form_state = array(); $form_state['values']['test'] = $this->randomName(); $form_state['values']['options'] = 'foo'; + $form_state['values']['op'] = 'Submit'; $this->formBuilder->submitForm($form_arg, $form_state); - $errors = $this->formBuilder->getErrors(); - $this->assertNull($errors); + $errors = $this->formBuilder->getErrors($form_state); + $this->assertEmpty($errors); $form_state = array(); $form_state['values']['test'] = $this->randomName(); $form_state['values']['options'] = $this->randomName(); $form_state['values']['op'] = 'Submit'; $this->formBuilder->submitForm($form_arg, $form_state); - $errors = $this->formBuilder->getErrors(); + $errors = $this->formBuilder->getErrors($form_state); $this->assertNotEmpty($errors['options']); } /** + * Tests the setErrorByName() method. + * + * @param array|null $limit_validation_errors + * The errors to limit validation for, NULL will run all validation. + * @param array $expected_errors + * The errors expected to be set. + * + * @dataProvider providerTestSetErrorByName + */ + public function testSetErrorByName($limit_validation_errors, $expected_errors) { + $form_id = 'test_form_id'; + $expected_form = $form_id(); + $expected_form['actions']['submit']['#submit'][] = 'test_form_id_custom_submit'; + $expected_form['actions']['submit']['#limit_validation_errors'] = $limit_validation_errors; + + $form_arg = $this->getMockForm($form_id, $expected_form); + $form_builder = $this->formBuilder; + $form_arg->expects($this->once()) + ->method('validateForm') + ->will($this->returnCallback(function (array &$form, array &$form_state) use ($form_builder) { + $form_builder->setErrorByName('test', $form_state, 'Fail 1'); + $form_builder->setErrorByName('test', $form_state, 'Fail 2'); + $form_builder->setErrorByName('options', $form_state); + })); + + $form_state = array(); + $form_state['values']['test'] = $this->randomName(); + $form_state['values']['options'] = 'foo'; + $form_state['values']['op'] = 'Submit'; + $this->formBuilder->submitForm($form_arg, $form_state); + + $errors = $this->formBuilder->getErrors($form_state); + $this->assertSame($expected_errors, $errors); + } + + /** + * Provides test data for testing the setErrorByName() method. + * + * @return array + * Returns some test data. + */ + public function providerTestSetErrorByName() { + return array( + // Only validate the 'options' element. + array(array(array('options')), array('options' => '')), + // Do not limit an validation, and, ensuring the first error is returned + // for the 'test' element. + array(NULL, array('test' => 'Fail 1', 'options' => '')), + // Limit all validation. + array(array(), array()), + ); + } + + /** + * Tests the getError() method. + * + * @dataProvider providerTestGetError + */ + public function testGetError($parents, $expected = NULL) { + $form_state = array(); + // Set errors on a top level and a child element, and a nested element. + $this->formBuilder->setErrorByName('foo', $form_state, 'Fail 1'); + $this->formBuilder->setErrorByName('foo][bar', $form_state, 'Fail 2'); + $this->formBuilder->setErrorByName('baz][bim', $form_state, 'Fail 3'); + + $element['#parents'] = $parents; + $error = $this->formBuilder->getError($element, $form_state); + $this->assertSame($expected, $error); + } + + /** + * Provides test data for testing the getError() method. + * + * @return array + * Returns some test data. + */ + public function providerTestGetError() { + return array( + array(array('foo'), 'Fail 1'), + array(array('foo', 'bar'), 'Fail 1'), + array(array('baz')), + array(array('baz', 'bim'), 'Fail 3'), + array(array($this->randomName())), + array(array()), + ); + } + + /** * Tests the getCache() method. */ public function testGetCache() { @@ -487,10 +566,7 @@ public function testGetCache() { // FormBuilder::buildForm() will be called 3 times, but the form object will // only be called twice due to caching. - $form_arg = $this->getMock('Drupal\Core\Form\FormInterface'); - $form_arg->expects($this->exactly(2)) - ->method('buildForm') - ->will($this->returnValue($expected_form)); + $form_arg = $this->getMockForm(NULL, $expected_form, 2); // The CSRF token and the user authentication are checked each time. $this->csrfToken->expects($this->exactly(3)) @@ -549,10 +625,7 @@ public function testSendResponse() { ->method('prepare') ->will($this->returnValue($expected_form)); - $form_arg = $this->getMock('Drupal\Core\Form\FormInterface'); - $form_arg->expects($this->any()) - ->method('buildForm') - ->will($this->returnValue($expected_form)); + $form_arg = $this->getMockForm(NULL, $expected_form); // Do an initial build of the form and track the build ID. $form_state = array(); @@ -562,6 +635,42 @@ public function testSendResponse() { } /** + * Provides a mocked form object. + * + * @param string $form_id + * (optional) The form ID to be used. If none is provided, the form will be + * set to expect that getFormId() will never be called. + * @param mixed $expected_form + * (optional) If provided, the expected form response for buildForm() to + * return. Defaults to NULL. + * @param int $count + * (optional) The number of times the form is expected to be built. Defaults + * to 1. + * + * @return \PHPUnit_Framework_MockObject_MockObject|\Drupal\Core\Form\FormInterface + * The mocked form object. + */ + protected function getMockForm($form_id = NULL, $expected_form = NULL, $count = 1) { + $form = $this->getMock('Drupal\Core\Form\FormInterface'); + if ($form_id) { + $form->expects($this->once()) + ->method('getFormId') + ->will($this->returnValue($form_id)); + } + else { + $form->expects($this->never()) + ->method('getFormId'); + } + + if ($expected_form) { + $form->expects($this->exactly($count)) + ->method('buildForm') + ->will($this->returnValue($expected_form)); + } + return $form; + } + + /** * Asserts that the expected form structure is found in a form for a given key. * * @param array $expected_form @@ -734,6 +843,8 @@ function test_form_id() { ); return $form; } + function test_form_id_custom_submit(array &$form, array &$form_state) { + } if (!defined('WATCHDOG_ERROR')) { define('WATCHDOG_ERROR', 3);