1

I generate a sample Class form (and routing) with the drupal console.

Then, I have my class with some defaults generated methods ; getFormId, buildForm...

When the user go to the url path defined in the routing file, the buildForm method is called for build the the form. I want call another function for check some datas before the buildForm method :

I function like :

function a_check_function_or_method_before_buildForm(...){
    // - Check some datas
    // - If all is ok, the buildForm can be called
    // - Else, if the custom function detect an error, the buildForm isn't called and the user is redirected to an error page
}

Is it possible to do that ? how can I do that ?

Thank you =)

2

You can do all that inside of buildForm():

use Symfony\Component\HttpKernel\Exception\HttpException;

public function buildForm(array $form, FormStateInterface $form_state) {

  $data = a_check_function_or_method_before_buildForm();

  // throw an exception
  if (empty($data)) {
    throw new HttpException(500, 'No data connection.');
  }

  // or return an empty form with an error message
  if (empty($data)) {
    return $form['#markup'] = '<h1>No data could be collected!</h1>';
  }

  // build the form with $data

}

Another possibility would be to call first a controller, which then decides what to do, return a form or something else.

  • I want separate check code and build form. Your another possibility seems I'm looking for ! From the controller, how can I build/return the form ? I just need return \Drupal::formBuilder()->getForm(Drupal\example\Form\ExampleForm::class) ? its good ? – user2137454 Sep 18 '16 at 10:57
  • Yes, if you want you can include a second parameter with your data. – 4k4 Sep 18 '16 at 11:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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