Kurs Svelte i SvelteKit · Moduł 13: Akcje formularzy

Targ w Birce - Form Actions

2 min czytania ·
W tej lekcji3

Witaj na targu w Birce! Tutaj wikingowie handlują i zawierają umowy. Form Actions w SvelteKit to sposób na obsługę formularzy po stronie serwera.

Podstawowy formularz

<!-- src/routes/warriors/new/+page.svelte -->
<form method="POST">
  <input name="name" placeholder="Imię wojownika" required />
  <input name="strength" type="number" placeholder="Siła" required />
  <button type="submit">Dodaj wojownika</button>
</form>
// src/routes/warriors/new/+page.server.js
export const actions = {
  default: async ({ request }) => {
    const data = await request.formData();
    const name = data.get('name');
    const strength = data.get('strength');

    // Zapisz do bazy
    await db.warriors.create({ name, strength: Number(strength) });

    return { success: true };
  }
};

Named actions

// +page.server.js
export const actions = {
  create: async ({ request }) => {
    // ...
  },
  delete: async ({ request }) => {
    // ...
  }
};
<form method="POST" action="?/create">
  <!-- ... -->
</form>

<form method="POST" action="?/delete">
  <input type="hidden" name="id" value={warrior.id} />
  <button>Usuń</button>
</form>

Zwracanie danych

To, co zwróci akcja, trafia do strony jako prop form. W Svelte 5 odbierasz go przez $props(), razem z data, jeśli strona go potrzebuje: let { data, form } = $props();.

<script>
  let { form } = $props();
</script>

{#if form?.success}
  <p class="success">Wojownik dodany!</p>
{/if}

{#if form?.error}
  <p class="error">{form.error}</p>
{/if}

<form method="POST">
  <!-- ... -->
</form>

Targ wymaga negocjacji - formularze wymagają walidacji!

Kod do tej lekcji: App.svelte
<script>
  // Targ w Birce - Form Actions
  // Formularze bez JavaScript na kliencie

  let warriors = $state([
    { id: 1, name: 'Ragnar', strength: 95 },
    { id: 2, name: 'Bjorn', strength: 90 }
  ]);

  let formData = $state({ name: '', strength: 50 });
  let message = $state('');

  // Symulacja form action
  function handleSubmit(e) {
    e.preventDefault();

    if (!formData.name) {
      message = 'Imię jest wymagane!';
      return;
    }

    warriors = [...warriors, {
      id: Date.now(),
      name: formData.name,
      strength: formData.strength
    }];

    formData = { name: '', strength: 50 };
    message = 'Wojownik dodany!';

    setTimeout(() => message = '', 2000);
  }
</script>

<main class="birka">
  <h1>Targ w Birce - Form Actions</h1>
  <p class="subtitle">Formularze w SvelteKit</p>

  <section class="code">
    <h2>+page.server.js</h2>
    <pre>
export const actions = {"{"}
  default: async ({"{"} request {"}"}) => {"{"}
    const data = await request.formData();
    const name = data.get('name');

    // Walidacja
    if (!name) {"{"}
      return fail(400, {"{"} error: 'Imię wymagane' {"}"});
    {"}"}

    // Zapisz do bazy
    await db.warriors.create({"{"} name {"}"});

    return {"{"} success: true {"}"};
  {"}"}
{"}"};
    </pre>
  </section>

  <section class="form-section">
    <h2>Dodaj wojownika</h2>

    <!-- W SvelteKit: method="POST" wystarczy -->
    <form onsubmit={handleSubmit}>
      <div class="field">
        <label for="name">Imię wojownika</label>
        <input
          id="name"
          name="name"
          bind:value={formData.name}
          placeholder="np. Ivar"
        />
      </div>

      <div class="field">
        <label for="strength">Siła ({formData.strength})</label>
        <input
          type="range"
          id="strength"
          name="strength"
          bind:value={formData.strength}
          min="1"
          max="100"
        />
      </div>

      <button type="submit">Dodaj wojownika</button>
    </form>

    {#if message}
      <p class="message">{message}</p>
    {/if}
  </section>

  <section class="list">
    <h2>Wojownicy ({warriors.length})</h2>
    {#each warriors as warrior (warrior.id)}
      <div class="warrior">
        <span>{warrior.name}</span>
        <span class="strength">{warrior.strength}</span>
      </div>
    {/each}
  </section>
</main>

<style>
  .birka {
    font-family: 'Georgia', serif;
    max-width: 500px;
    margin: 0 auto;
    padding: 2rem;
    background: #1a0f0a;
    color: #e8d5b7;
    min-height: 100vh;
  }

  h1 {
    color: #d4af37;
    text-align: center;
  }

  .subtitle {
    text-align: center;
    color: #8b7355;
  }

  section {
    background: rgba(212, 175, 55, 0.1);
    border: 1px solid #d4af37;
    border-radius: 8px;
    padding: 1rem;
    margin: 1rem 0;
  }

  h2 {
    color: #d4af37;
    font-size: 1rem;
    margin-top: 0;
  }

  pre {
    background: rgba(0,0,0,0.5);
    padding: 1rem;
    border-radius: 4px;
    font-size: 0.8rem;
    overflow-x: auto;
  }

  .field {
    margin-bottom: 1rem;
  }

  label {
    display: block;
    margin-bottom: 0.25rem;
    color: #d4af37;
  }

  input[type="text"],
  input[name="name"] {
    width: 100%;
    padding: 0.75rem;
    background: rgba(0,0,0,0.3);
    border: 1px solid #3d2914;
    border-radius: 4px;
    color: #e8d5b7;
  }

  input[type="range"] {
    width: 100%;
  }

  button {
    width: 100%;
    padding: 0.75rem;
    background: #3d2914;
    color: #e8d5b7;
    border: 1px solid #d4af37;
    border-radius: 4px;
    cursor: pointer;
    font-size: 1rem;
  }

  button:hover {
    background: #4d3924;
  }

  .message {
    margin-top: 1rem;
    padding: 0.75rem;
    background: rgba(144, 238, 144, 0.1);
    border-radius: 4px;
    text-align: center;
  }

  .warrior {
    display: flex;
    justify-content: space-between;
    padding: 0.75rem;
    background: rgba(0,0,0,0.3);
    border-radius: 4px;
    margin-bottom: 0.5rem;
  }

  .strength {
    color: #ffd700;
  }
</style>

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Gdzie definiujemy form actions w SvelteKit?

Zadania praktyczne w grze

  • Edytor kodu

    Uzupełnij atrybut action formularza

  1. PytanieMiejsce definicji form actions
  2. Zadanie z kodemPraktyka: Formularz z akcją create

Przydatne artykuły