Skip to content

Instantly share code, notes, and snippets.

@RuZniki
Last active November 10, 2023 09:39
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save RuZniki/099883da38fdc86614051705e3f4370f to your computer and use it in GitHub Desktop.
Save RuZniki/099883da38fdc86614051705e3f4370f to your computer and use it in GitHub Desktop.
Drupal 8 Adding a Reset Button to a form
<?php
/**
* Implements template_preprocess_form().
*/
function TEMPLATE_preprocess_form(&$vars) {
$vars['form']['actions']['reset'] = [
'#type' => 'html_tag',
'#tag' => 'input',
'#attributes' => [
'class' => 'button',
'type' => 'reset',
'value' => t('Reset'),
],
];
}
@iberezovchuk
Copy link

Thanks a lot! Very helpful.

@JPustkuchen
Copy link

Thank you! :)

I still think Core should add reset and button as FAPI types, but that's a different topic.

Perhaps you'd like to translate the value?
'value' => $this->t('Reset'),

@RuZniki
Copy link
Author

RuZniki commented Nov 10, 2023

@JPustkuchen thanks for your suggestion. I update the gist.
If you need more example you can find them in the core:

  // Example from \Drupal\dblog\Form\DblogFilterForm.
  public function buildForm(array $form, FormStateInterface $form_state) {
    //...
    if (!empty($session_filters)) {
      $form['filters']['actions']['reset'] = [
        '#type' => 'submit',
        '#value' => $this->t('Reset'),
        '#limit_validation_errors' => [],
        // callback to reset form values.
        '#submit' => ['::resetForm'],
      ];
    }
    //...
  }

  public function resetForm(array &$form, FormStateInterface $form_state) {
    $this->getRequest()->getSession()->remove('dblog_overview_filter');
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment