0

How do I add a reset button to a form? I have a form with a CKEditor and other fields, plus hidden fields. How do I reset the form so all fields are empty?

5
  • Does this answer your question? How to add reset button to forms? Commented Nov 28, 2023 at 20:22
  • I am sorry you don't like the old answer but AFAIK the answer is the same. codimth.com/blog/web/drupal/add-reset-button-forms-drupal-8 Commented Nov 28, 2023 at 21:13
  • You may need $form_state->setRebuild() in the submit handler. Commented Nov 28, 2023 at 21:34
  • NP. I've seen what you are suggesting, but the problem is similar... it is a submit button. Nothing I have come across has shown me how to keep the form from submitting. Another solution has the $form_state->setRebuild() in it, but still CKEditor and hidden fields retain their value. At this point it is easier to make the button reload the page than anything else. From my POV that is not a solution. Commented Nov 28, 2023 at 21:44
  • One option is to use #ajax on the submit button, and $form_state->setValue in the submit handler to clear the relevant values (with the ->setRebuild too) Commented Nov 29, 2023 at 9:12

1 Answer 1

0

I was able to get this to work.

Within the buildForm() method, part of the form array contains this for the reset button:

$form['rmdrs_form_reset_button'] = array( '#type' => 'submit', '#value' => t('Reset'), '#limit_validation_errors' => TRUE, '#submit' => ['::reminderFormReset'], ); 

Also in that Form class I have method for handling the reset:

public function reminderFormReset($form, &$form_state) { $form_state->setRebuild(FALSE); } 

The downside is that it is, IMHO, a glorified page reload. The button acts like a submit button, but instead calls the reminderFormReset() method in the same class.

2
  • Is limit_validation_errors anything to do with the solution or may that be removed? Commented Nov 29, 2023 at 21:24
  • 1
    '#limit_validation_errors' => TRUE, was added to stop the action of validation that normally happens when submit is called. Without it validation of HTML5 required fields would take place. At least that is my limited understanding of it. Commented Nov 29, 2023 at 22:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.