Upload with Turbo
An UploadType form lives in a Turbo Frame. A validation error swaps only the frame, and the
photos stay. A valid album comes back as a Turbo Stream: added to the list, form reset,
no page reload.
Albums
Save an album without a name first: only the frame changes, and the photos stay.
A form in a Turbo Frame
The form sits in a <turbo-frame>. Turbo submits it with fetch, and the rest
of the page stays in place.
Save without an album name: the server answers 422, Turbo swaps the frame, and
the photos are still attached. Each one is a signed reference, so nothing is
sent again.
<turbo-frame id="upload-gallery-form">
{{ form_start(form, {attr: {novalidate: 'novalidate'}}) }}
{{ form_row(form.photos) }}
{{ form_row(form.album) }}
<button type="submit" class="UploadStage_submit">Save album</button>
{{ form_end(form) }}
</turbo-frame>
One action, two answers
A valid album answers with a Turbo Stream when Turbo sent the form, and with a redirect otherwise. The same action works with and without JavaScript.
31if ($form->isSubmitted() && $form->isValid()) {
32 /** @var list<UploadedFile> $photos */
33 $photos = $form->get('photos')->getData() ?? [];
34 $album = $form->get('album')->getData();
35 // A real application moves the photos to their final place here. This public server
36 // destroyed them already: the page only needs their names and sizes.
37
38 // Without JavaScript, Turbo is not there: fall back to a redirect.
39 if (TurboBundle::STREAM_FORMAT !== $request->getPreferredFormat()) {
40 $this->addFlash('turbo_upload_success', \sprintf('Album "%s" received. Photos destroyed on arrival: demo server.', $album));
41
42 return $this->redirectToRoute('app_demo_upload_turbo');
43 }
44
45 $request->setRequestFormat(TurboBundle::STREAM_FORMAT);
46
47 return $this->render('demos/upload/turbo/success.stream.html.twig', [
48 'album' => $album,
49 'photos' => $photos,
50 'form' => $this->createForm(UploadGalleryForm::class),
51 ]);
52}
Add the album, reset the form
The stream prepends the album to the list and replaces the frame with an empty form, ready for the next photos.
<turbo-stream action="prepend" target="upload-albums">
<template>
{{ include('demos/upload/turbo/_album.html.twig') }}
</template>
</turbo-stream>
<turbo-stream action="remove" target="upload-albums-empty"></turbo-stream>
<turbo-stream action="replace" target="upload-gallery-form">
<template>
{{ include('demos/upload/turbo/_gallery_form.html.twig') }}
</template>
</turbo-stream>