Skip to content
Optima docs
SDKsAndroid SDK

Forms

Android SDK v1.4.0 — Forms

This iteration ships headless form loading and submission — forms.load/the bound submit — plus a link into the hosted, server-rendered form page for cases where a fully native form isn't worth building yet. There is no native form-renderer composable (no OptimaForm(id) that draws inputs for you); see chapter 8 for why that differs from the Web SDK's forms.render.

Loading and submitting a form

suspend fun loadNewsletterForm(): FormResult = Optima.instance.forms.load("newsletter-signup")

forms.load(id, lang, assertion) (both optional; pass assertion for a logged-in visitor) returns a sealed FormResult:

  • FormResult.Loaded(definition, submit) — the happy path. definition: FormDefinition carries fields: List<FormField> (each with key, kind, inputType, label, placeholder, required, options for select/radio-style fields), plus successMessage, successRedirectUrl, doubleOptIn, and minSubmitIntervalSec. submit is a bound closure — suspend (Map<String, Any?>) -> SubmitResult — that already carries the form's render nonce internally; you never see or handle the nonce yourself.
  • FormResult.NotFound — the form id doesn't exist or isn't published.
  • FormResult.Failed(status, cause) — a network failure or an unexpected status.

A minimal Compose form built from a loaded definition:

@Composable
fun NewsletterForm(formId: String = "newsletter-signup") {
    var result by remember { mutableStateOf<FormResult?>(null) }
    var values by remember { mutableStateOf<Map<String, String>>(emptyMap()) }
    var outcome by remember { mutableStateOf<SubmitResult?>(null) }
    val scope = rememberCoroutineScope()

    LaunchedEffect(formId) { result = Optima.instance.forms.load(formId) }

    when (val r = result) {
        is FormResult.Loaded -> Column(Modifier.padding(16.dp)) {
            r.definition.fields.forEach { field ->
                OutlinedTextField(
                    value = values[field.key] ?: "",
                    onValueChange = { values = values + (field.key to it) },
                    label = { Text(field.label + if (field.required) " *" else "") },
                    modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
                )
            }
            Button(onClick = { scope.launch { outcome = r.submit(values) } }) { Text("Submit") }
            when (val o = outcome) {
                is SubmitResult.Accepted -> Text(r.definition.successMessage ?: "Thanks!", color = Color(0xFF2E7D32))
                is SubmitResult.Rejected -> Text("Please check your entries.", color = MaterialTheme.colorScheme.error)
                is SubmitResult.Failed -> Text("Something went wrong — try again.", color = MaterialTheme.colorScheme.error)
                null -> {}
            }
        }
        FormResult.NotFound -> Text("This form is no longer available.")
        is FormResult.Failed -> Text("Couldn't load the form — check your connection.")
        null -> CircularProgressIndicator()
    }
}

submit's value map accepts String, Boolean, Int, Long, and finite Double/Float; anything else for a given key is silently dropped (a debug log names the field) rather than failing the whole submission — so a stray null or an unexpected object type in your values map costs you that one field, not the user's submission.

The honeypot and the nonce, handled for you

Every submission includes an empty honeypot field (_hp) and the render nonce the form definition carried privately — both anti-bot measures the hosted form page also uses, and both are wired up inside submit(...) without any action on your part. You cannot see or tamper with either from the public API, by design: there is nothing to configure and nothing that can be gotten wrong here.

409 means "already submitted"

If the device has already submitted this form (the server enforces min_submit_interval_sec and/or a one-submission-per-device rule server-side), the submit endpoint answers 409, and the SDK treats that as a success, not an error: SubmitResult.Accepted(dropped = emptyList(), doubleOptIn = definition.doubleOptIn), and a FormSubmitted event fires the same as a genuine first-time acceptance. Don't special-case 409 in your own UI — by the time it reaches SubmitResult, it's already been normalized into the same "it worked" shape as a real 200.

Double opt-in

When definition.doubleOptIn is true (or the server's response to a submission says so — out.doubleOptIn in SubmitResult.Accepted reflects whatever the server actually decided, which can differ from the definition's declared default in edge cases), the profile's consent for whatever the form grants is not yet active — a confirmation email/link has to be completed first. There's nothing further for the SDK to do here: the confirmation flow itself runs entirely server-side (GET/POST /edge/v1/forms/confirm/:token, addressed by a link in an email, deliberately outside any mobile deep link — see the design spec's rationale that a GET must never mutate, so a mail-scanner can't manufacture consent). Surface doubleOptIn = true in your own UI as "check your email to confirm" copy, if your form's purpose warrants it.

Hosted pages

For a form you don't want to build a native screen for yet — a long multi-section form, or one that changes frequently and you'd rather not ship an app update for — open the operator's hosted, server-rendered page in a Custom Tab instead:

val url = Optima.instance.forms.pageUrl("https://edge.shop.example/edge/v1/pages/<sdk-key-token>/newsletter-signup")
CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(url))

forms.pageUrl(url) appends device_id=<id> as a query parameter (creating the ? if the URL doesn't already have one) — this is what lets the hosted page's own submission attribute back to the same device identity the rest of the SDK uses, so a form filled out in the Custom Tab and an identify(...) call made natively both resolve to the same profile. The hosted page URL itself (/edge/v1/pages/:token/:slug) is addressed by SDK-key token rather than by X-Edge-Key header, because a browser navigation — which a Custom Tab is — can't send a custom header; get the exact URL for a given form from the Optima console's forms admin screen.

On this page