0

I want to disable a form in Drupal 8.

In D7 you could've done it in an alter hook like this.

$form['form'] = ['#value' => 'the form you are looking for is gone!']

What can I do in Drupal 8?

What I tried so far:

function hook_form_FORM_ID_alter () {
  $form[] = []; // $form[] or $form both will not work.
  $form['dunnoWhatToWriteHere'] = [
    '#type' => 'markup',
    '#markup' => t('The form is gone),
  ];
}

What I suggested is that I would overwrite the $form array with an blank one but as I run my xdebug drupal seems to just ignore it because the $form array in its native status exists although I tried to overwrite it with a blank one.

Do I also have to call a Formbuilder?

 $form = [];
 $form['error'] = [
   '#type' => 'html_tag',
   '#tag' => 'p',
   '#value' => t('The form is gone'),
 ];

That one worked for me :)

5
  • 1
    Why not prevent access to the route by permission? Or throw an AccessDeniedHttpException?
    – Kevin
    Sep 1, 2016 at 14:18
  • how would u do that? examples? Sep 1, 2016 at 14:47
  • 1
    Is the form on it's own page, or embedded in a page? hook_form_alter still exists in Drupal 8, so it's a possible avenue; however it may not be the best one depending on your actual use case.
    – Chapabu
    Sep 1, 2016 at 15:28
  • Actually, you aren't disabling a form, but overriding it.
    – apaderno
    Sep 1, 2016 at 16:39
  • The form is rendered on an existing page and overriding it would do it in my use case.
    – DiDebru
    Sep 2, 2016 at 4:46

1 Answer 1

2

What I suggested is that I would overwrite the $form array with an blank one but as I run my xdebug drupal seems to just ignore it because the $form array in its native status exists although I tried to overwrite it with a blank one.

What you describe does look like caching. Drupal returns what is cached, without running the code to build the form again.

You don't give much information, but you did tell in the comments, the form is part of a rendered page. If the form would be a page on it's own, then this is about access. If you only want control if a part of the page is displayed, then this is about blocks. The first thing to try is to configure the visibility of the form block. If you can't configure it in ui, then there are several ways to put custom code in block or page level to remove the block. This depends when and where the block should be displayed.

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.