Add and Edit Form
Personal Catalogue: Android (Kotlin & Compose)
Course 1 ยท Chapter 6 ยท Forms, Validation and Hoisted State
So far the only way to put data in is a temporary button that inserts "Sample item". This chapter replaces it with the real thing: one form screen used for both adding and editing, whose labels change with the item type (a book has an "Author", a CD an "Artist", a film a "Director"), with validation, and with the state kept where it belongs. It also finishes two loose ends from Chapter 5: the Edit button will work, and the sample-item code is deleted.
OutlinedTextField shows errors, how a number keyboard is requested, and Google's pattern of
hoisting a text field's value and error flag into a view model. It did not give a complete example of a form, so the form's structure is my own design from those parts. The
exposed-dropdown API was reported to be changing between Material 3 versions, so this chapter deliberately avoids it and picks the type with chips.
One Form, Two Jobs
Adding and editing are the same screen with different starting values. A web developer will recognise this: Django's ModelForm is used for both create and update views. Here a route argument
decides which: an item id of 0 means "new item" (which is also what Room's auto-generated key defaults to), any other id means "edit that item".
| Concern | Django ModelForm | This form |
|---|---|---|
| Create vs update | Two URLs, one form class | One route, FormRoute(itemId), 0 = new |
| Starting values | instance=item | The view model loads the item into its state |
| Validation | form.is_valid(), errors in the template | Computed in the view model, shown with isError and supportingText |
| Per-type labels | Template logic or a form subclass | One small function, labelsFor(type) |
| Saving | form.save() | repository.saveItem(item, tagIds) (Chapter 3) |
The Route
Add one line to Routes.kt. A default value lets the list's "+" button write FormRoute() for a new item.
Labels That Follow the Type
The spec's generic creator and formatDetail fields get friendlier names per type. A small function keeps this in one place, so the form, and later the detail screen, share it.
It matches on the seeded type names from Chapter 3, which is fine for a fixed list; if the list could grow, an enum or a column on ItemType would be the sturdier design.
The Form State and ViewModel
State hoisting means the text a user is typing is not stored inside the text field's composable; the field is handed its current value and told, through
onValueChange, when the user types. Google's validation guide does exactly this, keeping the value and its error flag in a view model. That is why the form can be pre-filled for an edit, why it
can be validated before saving, and why rotating the phone does not lose what was typed.
Two design choices. The year is held as text while it is being typed (an empty box is not a number) and only converted when saving. And errors are only shown after the first press of Save, so the form does not shout "Title is required" at someone who has not started typing.
Read save carefully, because it contains the chapter's two quiet traps. First, originalCreatedAt is carried through, so editing an item does not make it look newly added.
Second, existingTagIds is passed to saveItem: that function (Chapter 3) replaces the item's tag links, so an edit that passed an empty set would silently strip every tag. This
chapter's form has no tag controls yet, so it must preserve them; Chapter 7 adds the controls and replaces the preserved set with the user's choice. The isSaving guard stops a double-tap from saving
twice.
The Form Screen
Look at what the stateless FormContent does not have: no remember, no view model, no repository. Every character the user types goes through
onValueChange to the view model and returns as state.title. That is the full meaning of hoisted state, and it is why the labels update the instant a different type chip is tapped: the
chip changes typeId in the state, labelsFor is called again on the next draw, and the field labels change while the typed text stays.
Wiring and Clean-up
Three small edits finish the chapter.
- NavHost. Add the form destination, and make both buttons navigate to it:
composable<ListRoute> { ListScreen( onAddClick = { navController.navigate(FormRoute()) }, onItemClick = { id -> navController.navigate(DetailRoute(id)) } ) } composable<DetailRoute> { DetailScreen( onBack = { navController.popBackStack() }, onEditClick = { id -> navController.navigate(FormRoute(id)) } ) } composable<FormRoute> { FormScreen(onDone = { navController.popBackStack() }) }
- DetailScreen. Its
onEditClickmust now carry the id. Change the parameter toonEditClick: (Long) -> Unitand, inDetailScreen(notDetailContent), passonEditClick = { (state as? DetailUiState.Found)?.let { onEditClick(it.details.item.id) } }toDetailContent, which keeps its() -> Unit. - List. In
ListScreenchangeonAddClick = viewModel::addSampleItemtoonAddClick = onAddClick, then deleteaddSampleItemfromListViewModel, along with the now-unusedItemimport.
Run it: tap "+", pick CD (the label becomes "Artist"), fill in a title, and Save. Open the item, tap the pencil, change the title, Save, and the detail screen updates itself through its Flow.
Try Save with an empty title to see the error message.
SavedStateHandle can cover that case, and a real app
with long forms might use it; for a form this short it is a reasonable thing to leave out. The form also has no tag controls (Chapter 7) and no duplicate warning (Chapter 9).
Form with TextFields bound to @State (or an @Observable draft object) plays the same role,
and Binding is the iOS spelling of "value in, change out". The two courses use the same per-type labels and the same rules: title required, year optional but plausible.
Challenges
Add the route, labelsFor, the form state, view model and screen, make the three wiring edits, and remove addSampleItem. Add one item of each type, and for each write
down the label shown for the creator field. Then edit one of them and confirm its creation date on the detail screen did not change.
Make the title field trim leading spaces as the user types, and make the year error appear immediately if the user types something outside 1000 to the coming year, rather than waiting for Save. Say which function you changed in each case and whether the change belongs in the view model or the composable.
๐ View solutionExplain what would go wrong in an edit if save passed emptySet() as the tag ids, and what would go wrong if it passed System.currentTimeMillis() as
createdAt. For each, say which screen would show the damage and when.
Chapter 6 Quick Reference
- One form for add and edit:
@Serializable data class FormRoute(val itemId: Long = 0L); 0 means new - Hoisted state: the field gets
valueandonValueChange; the view model owns the text; derived flags (titleError,isValid) are computed from it OutlinedTextField(isError = ..., supportingText = { ... }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))- Show errors only after the first Save attempt (
showErrors) - Keep the year as text while typing; convert with
toIntOrNull()on save - Labels per type from one function,
labelsFor(typeName) - Edits must preserve what the form does not show:
createdAtand the existing tag ids _state.update { it.copy(...) }is the safe way to change aMutableStateFlow
isError turns the field's label, indicator and icon to the error colour and tells accessibility services; that
supportingText is a composable slot under the field; that KeyboardOptions(keyboardType = KeyboardType.Number) is the documented way to ask for a number keyboard; that Google's
validation guide keeps the value and error flag in a view model and passes them to a stateless composable; and that ExposedDropdownMenu changed shape in a recent Material 3 alpha.Not checked, from general knowledge:
KeyboardCapitalization.Words; minLines on OutlinedTextField; that a @Serializable route class
with a default value can be created as FormRoute() and read back with toRoute (the default is my assumption); the first { it.isNotEmpty() } startup logic and its
behaviour if seeding is slow; the MutableStateFlow.update extension; and all code, none of which was compiled. I did not check what OutlinedTextField does with an
isError field when supportingText is empty, so the layout may jump by a line when an error appears.