Jump to main content

Forms

Building a form handler for your Svelte component.


Local Requests

Note that for the time being, this constructor assumes that all responses from Django will be valid JSON.

While you can use relatively ordinary HTML to build your forms out in your Svelte component, DxSvelte supplies FormSetup, a constructor which lets you build your own form handler.

It takes care of attaching CSRF tokens, preventing page redirects, and deserialising the response.

When using the constructor, remember to attach it to the form markup with the use:myForm syntax as seen below.

<script>
  import { FormSetup } from '@common';
  const myForm = FormSetup('/hello/');
</script>

<form use:myForm>
    <input type="text" name="username" autocomplete="username"/>
    <input type="password" name="password" autocomplete="current-password"/>
    <button type="submit">Login</button>
</form>

Attaching Callbacks

You can also pass a callback function as the second argument to the constructor if you want something to happen in the front-end following a response.

<script>
  import { FormSetup } from '@common';
  // Create a callback function which runs on the front-end upon a response
  function loggerCallbackFunction(response) {
    console.log(response);
  };
  const myForm = FormSetup('/hello/', loggerCallbackFunction);
</script>

<form use:myForm>
    <input type="text" name="username" autocomplete="username"/>
    <input type="password" name="password" autocomplete="current-password"/>
    <button type="submit">Login</button>
</form>