Skip to content

Tutorial: a multi-step wizard ​

Build a three-step ticket wizard: subject → body → confirm and submit. The server guarantees steps can't be skipped, and when any step fails validation the page stays on that step.

1. Decide where state lives first ​

OptionSkip protectionSurvives a reloadRound trips
A. Stateful Linker, one call per step✅ The server blocks it❌One per step
B. Keep it in client state, submit once at the endValidated together at the end❌One
C. A draft row in the DB✅✅One per step

This tutorial builds A, with B at the end.

2. Migration and model ​

rust
// database/migrations/2026_12_02_000001_create_tickets_table.rs
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .create("tickets", |table| {
            table.id();
            table.foreign_id("user_id").constrained().cascade_on_delete();
            table.string("subject");
            table.text("body");
            table.timestamps();
        })
        .await
}
rust
// src/models/ticket.rs
use laravel::model::model;
use laravel::time::Timestamp;

#[model]
pub struct Ticket {
    pub id: i64,
    pub user_id: i64,
    pub subject: String,
    pub body: String,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

3. The component ​

rust
// src/cg/ticket_wizard.rs
use cg_component::runtime::linker::{Action, Args, LinkerComponent, LinkerContext, LinkerResponse, messages};
use laravel::model::create;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::models::Ticket;

#[derive(Default, Serialize, Deserialize)]
pub struct TicketWizard {
    step: u8,
    subject: String,
    body: String,
}

impl LinkerComponent for TicketWizard {
    const ALIAS: &'static str = "ticketWizard";
    const METHODS: &'static [&'static str] = &["saveSubject", "saveBody", "submit", "back"];

    async fn mount(&mut self, _: &LinkerContext, _: &Args) -> laravel::Result<()> {
        self.step = 1;
        Ok(())
    }

    async fn call(&mut self, context: &LinkerContext, method: &str, args: Args) -> laravel::Result<LinkerResponse> {
        match method {
            "saveSubject" => {
                let subject = text(&args, "subject");
                if subject.is_empty() || subject.chars().count() > 120 {
                    return Ok(LinkerResponse::validation([("subject", "A subject is required, at most 120 characters.")]));
                }
                self.subject = subject;
                self.step = 2;
                Ok(self.show().then(Action::focus("#ticket-body")))
            }
            "saveBody" => {
                if self.step < 2 {
                    return Ok(LinkerResponse::policy(messages::POLICY));
                }
                let body = text(&args, "body");
                if body.is_empty() || body.chars().count() > 5000 {
                    return Ok(LinkerResponse::validation([("body", "A body is required, at most 5000 characters.")]));
                }
                self.body = body;
                self.step = 3;
                Ok(self.show().data("previewSubject", &self.subject))
            }
            "submit" => {
                if self.step != 3 {
                    return Ok(LinkerResponse::policy(messages::POLICY));
                }
                let user_id: i64 = context.user.parse()?;
                let ticket = create!(Ticket {
                    user_id: user_id,
                    subject: &self.subject,
                    body: &self.body,
                })
                .await?;
                self.step = 4;
                Ok(self.show().then(Action::toast("success", &format!("Created #{}", ticket.id))))
            }
            "back" => {
                let to = args.get("to").and_then(Value::as_u64).unwrap_or(1).clamp(1, 2) as u8;
                self.step = to.min(self.step);
                Ok(self.show())
            }
            _ => unreachable!("METHODS lists every method"),
        }
    }
}

impl TicketWizard {
    fn show(&self) -> LinkerResponse {
        LinkerResponse::ok().data("step", self.step)
    }
}

fn text(args: &Args, key: &str) -> String {
    args.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_owned()
}

Key points:

  • step is a struct field, stored in the server cache. saveBody and submit check it first: this is a server-side guard the browser can't change.
  • submit reads no parameters at all; it's just "the button was pressed". Subject and body come from the values the server remembered.
  • back can only go backwards (to.min(self.step)), and its parameter is clamped to 1–2.
  • A validation failure doesn't advance rev or save state, so a failed call can't change step.

To register it: add mod ticket_wizard; and pub use ticket_wizard::TicketWizard; to src/cg/mod.rs, and call linker::register::<TicketWizard>() in register().

4. Handler ​

rust
// src/http/handlers/tickets.rs
use cg_component::runtime::{self, Allow, linker};
use laravel::prelude::*;
use laravel::view::{Html, View};

use crate::cg::TicketWizard;
use crate::models::User;

pub async fn create(user: Authenticated<User>) -> laravel::Result<View> {
    let mount = linker::mount::<TicketWizard, User>(&user, linker::Args::new()).await?;
    let object = runtime::render_object("ticketWizard", &[Allow::StateRead, Allow::StateWrite]);

    Ok(view("tickets.create", data! {}).with_html("wizard_attrs", Html::raw(mount.html() + &object.render(&[]))))
}

Add route.get("/tickets/create", tickets::create); to src/routes/web.rs.

5. The template ​

html
{% extends "layouts/site.html" %}

{% block title %}New ticket{% endblock %}

{% block content %}
<main class="mx-auto grid max-w-xl gap-4 px-6 py-12"{{ wizard_attrs }} data-state-init="step=1">
    <ol class="flex gap-4">
        <li data-state-is-class="step=1:font-bold; step>1:text-green-700">Subject</li>
        <li data-state-is-class="step=2:font-bold; step>2:text-green-700">Body</li>
        <li data-state-is-class="step=3:font-bold; step>3:text-green-700">Confirm</li>
    </ol>

    <form data-state-is="step=1">
        <input name="subject" data-state-bind="subject">
        {{ cg_button("Next", type="submit", attrs={"data-linker-call": "saveSubject", "data-linker-args": "form"}) }}
    </form>

    <form data-state-is="step=2">
        <textarea id="ticket-body" name="body" data-state-bind="body"></textarea>
        {{ cg_button("Back", variant="ghost", attrs={"data-linker-call": "back", "data-linker-args": "{\"to\":1}"}) }}
        {{ cg_button("Next", type="submit", attrs={"data-linker-call": "saveBody", "data-linker-args": "form"}) }}
    </form>

    <section data-state-is="step=3">
        <p>Subject: <strong data-state-text="previewSubject"></strong></p>
        {{ cg_button("Back", variant="ghost", attrs={"data-linker-call": "back", "data-linker-args": "{\"to\":2}"}) }}
        {{ cg_button("Submit", attrs={"data-linker-call": "submit", "data-linker-confirm": "Submit this ticket?"}) }}
    </section>

    <p data-state-is="step=4">Done!</p>
</main>
{% endblock %}

How it works:

  • Every method returns data.step, which is written to ticketWizard:step in client state, and data-state-is / -is-class switch the page automatically.
  • The client's step is only a display. If the user changes it to 3 in DevTools the page jumps ahead, but when they press "Submit" the server's step is still 1, and it returns policy.
  • data-state-bind keeps what was typed when the user goes back.
  • The buttons are made with cg_button, with the Linker attributes in attrs. JSON in attrs is escaped to {&quot;to&quot;:1}, and the browser turns it back into {"to":1} when it reads the attribute.

6. Check it ​

  1. Leave the subject empty and press Next → the error appears next to the field and you stay on step one.
  2. In the console run document.querySelector('[data-state-is="step=3"]').hidden = false, then press Submit → policy.
  3. Reload after submitting → back to step one (a new instance). That's the spec, not a bug.

A test skeleton (tests/tickets.rs):

rust
let post = |body| app.post(endpoints::linker_url()).acting_as(&owner).json(body);

post(call(0, "submit", json!({}))).await.assert_json(json!({ "ok": false, "kind": "policy" }));
post(call(0, "saveSubject", json!({ "subject": "" }))).await.assert_json(json!({ "ok": false, "kind": "validation" }));
post(call(0, "saveSubject", json!({ "subject": "The printer is broken" }))).await
    .assert_json(json!({ "ok": true, "data": { "step": 2 }, "rev": 1 }));
post(call(1, "saveBody", json!({ "body": "Paper jam" }))).await
    .assert_json(json!({ "ok": true, "data": { "step": 3, "previewSubject": "The printer is broken" }, "rev": 2 }));
post(call(2, "submit", json!({}))).await.assert_json(json!({ "ok": true, "data": { "step": 4 }, "rev": 3 }));
assert_eq!(Ticket::query().count().await?, 1);

Note that failed calls don't advance rev: it stays 0 until the first success.

7. Variant: submit once (option B) ​

Every step switches only on the client, with a single submit at the end. It saves round trips, but validation happens all at once, and the bad field may be in a hidden step, so catch brings the page back to it:

html
<div{{ quick_attrs }} data-state-init="step=1">
    <form>
        <fieldset data-state-is="step=1">
            <input name="subject">
            <button type="button" data-state-set="step=2">Next</button>
        </fieldset>
        <fieldset data-state-is="step=2">
            <textarea name="body"></textarea>
            {{ cg_button("Submit", type="submit", attrs={"data-linker-call": "submit", "data-linker-args": "form"}) }}
        </fieldset>
    </form>
</div>
rust
async fn call(&mut self, ctx: &LinkerContext, _: &str, args: Args) -> laravel::Result<LinkerResponse> {
    let subject = text(&args, "subject");
    if subject.is_empty() || subject.chars().count() > 120 {
        // catch, not then: the whole call failed, so only catch / always run.
        // Without moving step back, the error is drawn in a hidden panel and the user only sees "nothing happened".
        return Ok(LinkerResponse::validation([("subject", "A subject is required, at most 120 characters.")])
            .catch(Action::state_set("ticketQuick", "step", 1)));
    }

    let body = text(&args, "body");
    if body.is_empty() || body.chars().count() > 5000 {
        return Ok(LinkerResponse::validation([("body", "A body is required, at most 5000 characters.")])
            .catch(Action::state_set("ticketQuick", "step", 2)));
    }

    // Create the Ticket…
    Ok(LinkerResponse::ok().then(Action::toast("success", "Created")))
}

This component can be Stateless (const MODE: LinkerMode = LinkerMode::Stateless;): it doesn't need to remember anything. The scope of state.set must equal the render object's name (here ticketQuick).