Skip to content

Add a clear and reset methods to the form remote function #14210

@thomasmol

Description

@thomasmol

Describe the problem

The form remote function doesn't provide a way to clear form results or reset form fields programmatically.

E.g. I'd like to be able to do todosForm.clear() to clear the result property and todosForm.reset() to reset the associated form element.

These methods could help with:

  • Clear error/success messages after seeing them
  • Hiding/showing some other element based on the result
  • Reset form after submission for repeated use

Describe the proposed solution

I would like to see two new methods added to the RemoteForm interface:

  1. clear() - Clears the form result (could set result to undefined)
  2. reset() - Resets the form fields using the HTML form element's built-in reset() method

Example usage:

<script>
  import { myForm } from './form.remote.js';
</script>

<form {...myForm}>
  <input name="data" />
  <button type="submit">Submit</button>
</form>

<button onclick={() => myForm.clear()}>Clear Result</button>
<button onclick={() => myForm.reset()}>Reset Form</button>

{#if myForm.result}
  <p>Result: {myForm.result}</p>
{/if}

Alternatives considered

A workaround is to manually manage separate reactive variables to track form state/results:

<script>
  import { myForm } from './form.remote.js';
  
  let showResult = $state(false);
  let resultMessage = $state('');
  
  function clearResult() {
    showResult = false;
    resultMessage = '';
  }
  
  function resetForm(formElement) {
    formElement.reset();
  }
</script>

<form {...myForm.enhance(async ({ form, submit }) => {
  await submit();

  // Manual state management
  showResult = true;
  resultMessage = myForm.result;
})} bind:this={formElement}>
  <input name="data" />
  <button type="submit">Submit</button>
</form>

<button onclick={() => clearResult()}>Clear Result</button>
<button onclick={() => resetForm(formElement)}>Reset Form</button>

{#if showResult}
  <p>{resultMessage}</p>
{/if}

Importance

would make my life easier

Additional Information

I have created a possible implementation here: thomasmol#1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions