NaingAungLuu / form-conductor

A declarative form validation for Jetpack Compose
https://formconductor.naingaungluu.me
MIT License
59 stars 5 forks source link

How to get form data for onClick handler? #20

Closed jsmestad closed 1 year ago

jsmestad commented 1 year ago

I was wondering how to get the data out of the form and into somewhere an onClick handler can access it? I am getting the usual error @Composable invocations can only happen from the context of an @Composable function.

I assume calling a onClick handler with the form data is a popular option so it may be good to add to the sample.

This may be really obvious, I am new to Jetpack compose 🙃

NaingAungLuu commented 1 year ago

Hey @jsmestad Thanks for trying out the library and raising the first issue! Yes, we can actually access the form data from within the onClick which isn't a @Composable function

Let's say we have the following form:

@Composable
fun FormLayout() {
    form(SignUpFormData::class) {
        field(SignUpFormData::username) { .... }
        field(SignUpFormData::password) { ... }
        Button()
    }
}

Then, we can access form data as follows:

...
    form(SignUpFormData::class) {
        field(SignUpFormData::username) { .... }
        field(SignUpFormData::password) { ... }

        val formResult = this.formState.value
        Button(
            enabled = formResult is FormResult.Success,
            onClick = {
                when (formResult) {
                    is FormResult.Success -> {
                        // formResult.data returns SignUpFormData
                    }
                    is FormResult.Error -> {
                        // you can access formResult.failedRules
                    }
                    FormResult.NoInput -> {}
                }
            }
        )  {
      }
    }
...

The form composable opens up a FormScope where you can access it's result as a compose State just by using this keyword

Please try it out and let me know if you still have problems! And I suggest using the latest version 0.3.0 since it includes improved proguard rules for release mode stability and validate(), submit() apis.

I'll be updating the examples in the documentations as well!

NaingAungLuu commented 1 year ago

I'll be closing the issue hoping the above answered the question! You can re-open the issue for further questions