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.

What was run, and what was not
Nothing was compiled or run (no Android Studio here). My search confirmed how 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".

ConcernDjango ModelFormThis form
Create vs updateTwo URLs, one form classOne route, FormRoute(itemId), 0 = new
Starting valuesinstance=itemThe view model loads the item into its state
Validationform.is_valid(), errors in the templateComputed in the view model, shown with isError and supportingText
Per-type labelsTemplate logic or a form subclassOne small function, labelsFor(type)
Savingform.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.

@Serializable data class FormRoute(val itemId: Long = 0L)

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.

package com.example.catalogue.ui.form data class FieldLabels(val creator: String, val format: String) fun labelsFor(typeName: String?): FieldLabels = when (typeName) { "Book" -> FieldLabels(creator = "Author", format = "Format (hardcover, paperback...)") "CD" -> FieldLabels(creator = "Artist", format = "Format (album, single...)") "DVD", "Blu-ray" -> FieldLabels(creator = "Director", format = "Edition or region code") else -> FieldLabels(creator = "Creator", format = "Format") }

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.

package com.example.catalogue.ui.form import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.toRoute import com.example.catalogue.data.CatalogueRepository import com.example.catalogue.data.Item import com.example.catalogue.data.ItemType import com.example.catalogue.ui.navigation.FormRoute import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import java.util.Calendar data class FormUiState( val isEdit: Boolean = false, val types: List<ItemType> = emptyList(), val typeId: Long? = null, val title: String = "", val creator: String = "", val formatDetail: String = "", val yearText: String = "", val notes: String = "", val showErrors: Boolean = false, val isSaving: Boolean = false ) { val typeName: String? get() = types.firstOrNull { it.id == typeId }?.name val titleError: Boolean get() = title.isBlank() val yearError: Boolean get() = yearText.isNotEmpty() && yearText.toIntOrNull() !in 1000..(currentYear() + 1) val isValid: Boolean get() = !titleError && !yearError && typeId != null } private fun currentYear() = Calendar.getInstance().get(Calendar.YEAR) @HiltViewModel class FormViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val repository: CatalogueRepository ) : ViewModel() { private val itemId: Long = savedStateHandle.toRoute<FormRoute>().itemId private val _state = MutableStateFlow(FormUiState(isEdit = itemId != 0L)) val uiState: StateFlow<FormUiState> = _state.asStateFlow() // Kept outside the visible state: not edited here, but must survive a save (see below). private var originalCreatedAt: Long = System.currentTimeMillis() private var existingTagIds: Set<Long> = emptySet() init { viewModelScope.launch { repository.ensureSeeded() val types = repository.itemTypes.first { it.isNotEmpty() } _state.update { it.copy(types = types, typeId = it.typeId ?: types.first().id) } if (itemId != 0L) { repository.observeItem(itemId).first()?.let { found -> originalCreatedAt = found.item.createdAt existingTagIds = found.tags.map { it.id }.toSet() _state.update { it.copy( typeId = found.item.itemTypeId, title = found.item.title, creator = found.item.creator, formatDetail = found.item.formatDetail, yearText = found.item.releaseYear?.toString().orEmpty(), notes = found.item.notes ) } } } } } fun onTypeChange(id: Long) = _state.update { it.copy(typeId = id) } fun onTitleChange(v: String) = _state.update { it.copy(title = v) } fun onCreatorChange(v: String) = _state.update { it.copy(creator = v) } fun onFormatChange(v: String) = _state.update { it.copy(formatDetail = v) } fun onNotesChange(v: String) = _state.update { it.copy(notes = v) } fun onYearChange(v: String) { if (v.length <= 4 && v.all(Char::isDigit)) _state.update { it.copy(yearText = v) } } fun save(onSaved: () -> Unit) { val s = _state.value if (s.isSaving) return if (!s.isValid) { _state.update { it.copy(showErrors = true) } return } _state.update { it.copy(isSaving = true) } viewModelScope.launch { repository.saveItem( Item( id = itemId, title = s.title.trim(), creator = s.creator.trim(), formatDetail = s.formatDetail.trim(), releaseYear = s.yearText.toIntOrNull(), notes = s.notes.trim(), createdAt = originalCreatedAt, itemTypeId = s.typeId!! ), tagIds = existingTagIds ) onSaved() } } }

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

package com.example.catalogue.ui.form import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle @Composable fun FormScreen(onDone: () -> Unit, viewModel: FormViewModel = hiltViewModel()) { val state by viewModel.uiState.collectAsStateWithLifecycle() FormContent( state = state, onBack = onDone, onSave = { viewModel.save(onSaved = onDone) }, onTypeChange = viewModel::onTypeChange, onTitleChange = viewModel::onTitleChange, onCreatorChange = viewModel::onCreatorChange, onFormatChange = viewModel::onFormatChange, onYearChange = viewModel::onYearChange, onNotesChange = viewModel::onNotesChange ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun FormContent( state: FormUiState, onBack: () -> Unit, onSave: () -> Unit, onTypeChange: (Long) -> Unit, onTitleChange: (String) -> Unit, onCreatorChange: (String) -> Unit, onFormatChange: (String) -> Unit, onYearChange: (String) -> Unit, onNotesChange: (String) -> Unit ) { val labels = labelsFor(state.typeName) Scaffold( topBar = { TopAppBar( title = { Text(if (state.isEdit) "Edit item" else "Add item") }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Cancel") } }, actions = { TextButton(onClick = onSave, enabled = !state.isSaving) { Text("Save") } } ) } ) { innerPadding -> Column( modifier = Modifier .padding(innerPadding) .verticalScroll(rememberScrollState()) .padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { Text("Type", style = MaterialTheme.typography.labelLarge) LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { items(state.types, key = { it.id }) { type -> FilterChip( selected = state.typeId == type.id, onClick = { onTypeChange(type.id) }, label = { Text(type.name) } ) } } OutlinedTextField( value = state.title, onValueChange = onTitleChange, label = { Text("Title (required)") }, singleLine = true, isError = state.showErrors && state.titleError, supportingText = { if (state.showErrors && state.titleError) Text("Please enter a title") }, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Words), modifier = Modifier.fillMaxWidth() ) OutlinedTextField( value = state.creator, onValueChange = onCreatorChange, label = { Text(labels.creator) }, singleLine = true, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Words), modifier = Modifier.fillMaxWidth() ) OutlinedTextField( value = state.formatDetail, onValueChange = onFormatChange, label = { Text(labels.format) }, singleLine = true, modifier = Modifier.fillMaxWidth() ) OutlinedTextField( value = state.yearText, onValueChange = onYearChange, label = { Text("Year (optional)") }, singleLine = true, isError = state.showErrors && state.yearError, supportingText = { if (state.showErrors && state.yearError) Text("Enter a four-digit year") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), modifier = Modifier.fillMaxWidth() ) OutlinedTextField( value = state.notes, onValueChange = onNotesChange, label = { Text("Notes") }, minLines = 3, modifier = Modifier.fillMaxWidth() ) } } }

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.

  1. 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() }) }
  2. DetailScreen. Its onEditClick must now carry the id. Change the parameter to onEditClick: (Long) -> Unit and, in DetailScreen (not DetailContent), pass onEditClick = { (state as? DetailUiState.Found)?.let { onEditClick(it.details.item.id) } } to DetailContent, which keeps its () -> Unit.
  3. List. In ListScreen change onAddClick = viewModel::addSampleItem to onAddClick = onAddClick, then delete addSampleItem from ListViewModel, along with the now-unused Item import.

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.

Limits of This Form
The typed text is held in the view model, which survives rotation but not the system killing the app in the background. Google's 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).
Compare with the iOS course
In Personal Catalogue: iOS (Swift & SwiftUI) Chapter 6, a 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

Exercise 1

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.

๐Ÿ“„ View solution
Exercise 2

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 solution
Exercise 3

Explain 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.

๐Ÿ“„ View solution

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 value and onValueChange; 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: createdAt and the existing tag ids
  • _state.update { it.copy(...) } is the safe way to change a MutableStateFlow
Not Yet Verified
Checked (one web search on 2026-11-19): that 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.
Sources for This Chapter
Search results (2026-11-19): OutlinedTextField API reference; KeyboardOptions API reference; Validate input as the user types; ExposedDropdownMenuBox API reference; ViewModel and State in Compose. Only titles and short summaries in the search results were used.
Coming next
Personal Catalogue: Android (Kotlin & Compose) 7 adds tags: a managed list that never allows "Web Development" and "web development" to coexist, an autocomplete input on the form, tag chips, and the many-to-many writes that replace the preserved tag ids used in this chapter.