4

I have created a form following structure:

my_module
    |__
       src
         |__Form
                |__myform.php

I want to get the form_state in some() function in controller located at:

my_module
    |__
       src
         |__Controller
                     |__mycontroller.php

So that I can set error on one of my form element (say) - upload_container. And I will call function some():

static function some() {
$form_state->setErrorByName('upload_container', 'throw error while validating form');
}

here shown below as (in myform.php):

public function validateForm(array &$form, FormStateInterface $form_state) {
   mycontroller::some();
}

In D7, we do the same thing in a separate file example: common.inc

static function some() {
    form_set_error('upload_container', 'throw error while validating form');
    }

But in D8, How to set error on a form element via function located somewhere in controller file? I can't even get form_state in any third function which is located at controller.

1 Answer 1

5

Setting errors outside of validation isn't supported any more. From a related change record:

In Drupal 7, form validation functions could use either form_set_error() or form_error() to set errors for an element, and form_get_errors() to retrieve the errors for a given form. These were global functions, which just set or retrieved errors from the current form being processed. This worked fine for form validation functions, but could produce unexpected results when called from non-form functions (like a theme function).

In order to ensure that errors are associated with the correct form, you must now call the form error functions on $form_state.

Even if you got a reference to the form state in your controller, setting errors on it wouldn't do anything as the form wouldn't be validating (see this change record)

The best alternative is probably to use hook_form_alter and a validation method to the form which contains your logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.