Skip to content

Edit: useForm ​

useForm('put', url, data) with Precognition through {{bind … validate=true}}: dirty state, Discard, and errors before you save.

Open it in the live demo ↗

The page ​

gts
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { bind, Link, type PageSignature, useForm } from 'inertia-ember';

import {
  buttonClass,
  FieldError,
  inputClass,
  PageHeader,
  secondaryButtonClass,
  ValidMark,
} from '../../components/ui.gts';
import type { Idea, IdeaInput } from '../../types.ts';

export default class IdeasEdit extends Component<PageSignature<{ idea: Idea; categories: string[] }>> {
  // The remember key keeps unsaved edits in history: leave the page and press back, and they're still here.
  // withPrecognition checks each field against the server's rules as it changes (`validate=true` on bind).
  form = useForm<IdeaInput>(`Ideas/Edit:${this.args.props.idea.id}`, {
    title: this.args.props.idea.title,
    category: this.args.props.idea.category,
    body: this.args.props.idea.body,
  })
    .withPrecognition('put', `/ideas/${this.args.props.idea.id}`)
    .setValidationTimeout(300);

  save = (event: SubmitEvent): void => {
    event.preventDefault();
    // The Precognition endpoint doubles as the submit target.
    this.form.submit();
  };

  discard = (): void => {
    this.form.resetAndClearErrors();
  };

  <template>
    <PageHeader
      @eyebrow='useForm · bind · Precognition'
      @title='Edit idea'
      @lead='Form state lives in a useForm object; the bind modifier keeps each input and field in sync, and checks each field on the server as it changes.'
    />

    <form
      class='max-w-2xl space-y-5 rounded-2xl bg-white p-5 shadow-sm ring-1 ring-stone-200 sm:p-6'
      data-test-edit-form
      {{on 'submit' this.save}}
    >
      <div>
        <div class='mb-1 flex items-center justify-between gap-2'>
          <label class='block text-sm font-medium' for='title'>Title</label>
          <ValidMark @field='title' @valid={{this.form.valid 'title'}} />
        </div>
        <input id='title' class={{inputClass}} {{bind this.form 'title' validate=true}} />
        <FieldError @field='title' @message={{this.form.errors.title}} />
      </div>

      <div>
        <div class='mb-1 flex items-center justify-between gap-2'>
          <label class='block text-sm font-medium' for='category'>Category</label>
          <ValidMark @field='category' @valid={{this.form.valid 'category'}} />
        </div>
        <select id='category' class={{inputClass}} {{bind this.form 'category' validate=true}}>
          {{#each @props.categories as |category|}}
            <option value={{category}}>{{category}}</option>
          {{/each}}
        </select>
        <FieldError @field='category' @message={{this.form.errors.category}} />
      </div>

      <div>
        <div class='mb-1 flex items-center justify-between gap-2'>
          <label class='block text-sm font-medium' for='body'>Description</label>
          <ValidMark @field='body' @valid={{this.form.valid 'body'}} />
        </div>
        <textarea id='body' rows='8' class={{inputClass}} {{bind this.form 'body' validate=true}}></textarea>
        <FieldError @field='body' @message={{this.form.errors.body}} />
        <p class='mt-1 text-right font-mono text-xs text-stone-500'>{{this.form.body.length}} / 2000</p>
      </div>

      <div class='flex flex-wrap items-center gap-3'>
        <button type='submit' class={{buttonClass}} disabled={{this.form.processing}} data-test-save>
          {{if this.form.processing 'Saving…' 'Save changes'}}
        </button>
        <button
          type='button'
          class={{secondaryButtonClass}}
          disabled={{if this.form.isDirty false true}}
          {{on 'click' this.discard}}
        >Discard</button>
        <Link @href='/ideas/{{@props.idea.id}}' class='text-sm text-stone-600 hover:text-stone-900'>Back</Link>
        <span class='ml-auto text-xs {{if this.form.isDirty "text-amber-700" "text-stone-400"}}' data-test-dirty>
          {{if this.form.isDirty 'Unsaved changes' 'No changes'}}
        </span>
      </div>
    </form>
  </template>
}

Both forms post to the same handlers, store and update, in ideas.rs, which validate the same input:

rs
use laravel::axum::http::HeaderMap;
use laravel::broadcast::{self, Channel};
use laravel::head::{self, Head};
use laravel::inertia::{self, Page, props};
use laravel::model::{create, update};
use laravel::prelude::*;
use laravel::task;
use serde::Serialize;

use crate::events::IdeaVoted;
use crate::http::middleware::precognition;
use crate::models::{CATEGORIES, Comment, Idea};

#[laravel::query]
#[derive(Serialize)]
pub struct Filters {
    #[validate(max_length(100))]
    search: Option<String>,
    #[validate(one_of("frontend", "backend", "dx", "community"))]
    category: Option<String>,
}

#[laravel::input(fills = Idea)]
#[validate(anyone)]
pub struct IdeaInput {
    #[validate(required, min_length(4), max_length(120))]
    pub title: String,
    #[validate(required, min_length(10), max_length(2000))]
    pub body: String,
    #[validate(required, one_of("frontend", "backend", "dx", "community"))]
    pub category: String,
}

/// The list loads 12 ideas at a time as the visitor scrolls (`inertia::scroll_with`), filtered by the
/// query string, which the page changes with partial reloads.
pub async fn index(Query(filters): Query<Filters>) -> Page {
    let search = filters.search.clone().filter(|term| !term.trim().is_empty());
    let category = filters.category.clone();

    inertia::render(
        "Ideas/Index",
        props! {
            filters,
            categories => CATEGORIES,
            ideas => inertia::scroll_with(async move || {
                Idea::query()
                    .filter(search.as_ref().map(|term| Idea::title.contains(term) | Idea::body.contains(term)))
                    .filter(category.as_ref().map(|category| Idea::category.eq(category)))
                    .order_by(Idea::id.desc())
                    .paginate(12)
                    .await
                    .map(|page| page.with_query_string())
            }),
        },
    )
}

// #region show
/// `similar` is deferred: the page renders first and asks for it right after. `comments` is optional:
/// only sent when the page scrolls down to them. Both wait a little so the loading states show.
/// `idea` is live: when someone else votes, every open copy of the page reloads it.
pub async fn show(idea: Idea) -> laravel::Result<Page> {
    head::merge(Head::new().title(&idea.title));

    let idea_id = idea.id;
    let category = idea.category.clone();
    let comments_count = idea.comments().count().await?;

    Ok(inertia::render(
        "Ideas/Show",
        props! {
            idea => inertia::lazy(async move || Idea::find(idea_id).await)
                .live(inertia::on_channel::<IdeaVoted>(Channel::public(format!("ideas.{idea_id}"))?)),
            commentsCount => comments_count,
            similar => inertia::defer(async move || {
                task::sleep(1200.milliseconds()).await;

                Idea::query()
                    .filter(Idea::category.eq(&category) & Idea::id.ne(idea_id))
                    .order_by(Idea::votes.desc())
                    .limit(3)
                    .get()
                    .await
            }),
            comments => inertia::optional(async move || {
                task::sleep(700.milliseconds()).await;

                Comment::query()
                    .filter(Comment::idea_id.eq(idea_id))
                    .order_by(Comment::id.desc())
                    .get()
                    .await
            }),
        },
    ))
}
// #endregion show

pub async fn create() -> Page {
    head::merge(Head::new().title("New idea"));

    inertia::render("Ideas/Create", props! { categories => CATEGORIES })
}

/// With `Precognition: true` the input is only validated; nothing is saved.
pub async fn store(headers: HeaderMap, Valid(input): Valid<IdeaInput>) -> laravel::Result<Response> {
    if precognition::requested(&headers) {
        return Ok(precognition::passed());
    }

    let idea = create!(Idea { ..input }).await?;
    inertia::flash("toast", "Idea published.")?;

    Ok(Response::new(redirect!(show, &idea)))
}

pub async fn edit(idea: Idea) -> Page {
    head::merge(Head::new().title(format!("Edit · {}", idea.title)));

    inertia::render("Ideas/Edit", props! { idea, categories => CATEGORIES })
}

pub async fn update(mut idea: Idea, headers: HeaderMap, Valid(input): Valid<IdeaInput>) -> laravel::Result<Response> {
    if precognition::requested(&headers) {
        return Ok(precognition::passed());
    }

    update!(idea { ..input }).await?;
    inertia::flash("toast", "Changes saved.")?;

    Ok(Response::new(redirect!(show, &idea)))
}

pub async fn destroy(idea: Idea) -> laravel::Result<Redirect> {
    idea.delete().await?;
    inertia::flash("toast", "Idea deleted.")?;

    Ok(Redirect::to("/ideas"))
}

pub async fn vote(mut idea: Idea) -> laravel::Result<Redirect> {
    update!(idea { votes += 1 }).await?;
    // The tab that voted already reloads `idea`; tell the others.
    broadcast::event(IdeaVoted { idea_id: idea.id }).to_others().await?;

    Ok(Redirect::back())
}

Released under the MIT License.