Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add validation for dropdown menu #48

Closed
salauddin23shumon opened this issue Sep 25, 2022 · 2 comments
Closed

Add validation for dropdown menu #48

salauddin23shumon opened this issue Sep 25, 2022 · 2 comments

Comments

@salauddin23shumon
Copy link

This library is awesome, can we validate dropdown menu (spinner) with form_builder? If it is possible than show us how to implement it or if it is not possible than please add this validation too. thnx.

@LinusMuema
Copy link
Collaborator

Hello @salauddin23shumon

You can use either ChoiceState or SelectState then use any of the available validators.

I have implemented a dropdown input with ChoiceState and an OutlinedTextField. You just need to add the state to your formstate. Then in your activity/composable:

val options = listOf("Option 1", "Option 2", "Option 3", "Option 4")
val fieldState: ChoiceState = formState.getState("option")

var expanded by remember { mutableStateOf(false) }
var textFieldSize by remember { mutableStateOf(Size.Zero) }

val icon = if (expanded) Icons.Filled.ArrowDropUp
else Icons.Filled.ArrowDropDown

For the TextField:

OutlinedTextField(
    value = fieldState.value,
    enabled = false,   // Avoid manual input from the user
    onValueChange = {},
    label = { Text("Label") },
    modifier = Modifier
        .fillMaxWidth()
        .onGloballyPositioned { textFieldSize = it.size.toSize() } // Ensure the dropdown dialog is the same width as the input
        .clickable { expanded = !expanded },
    trailingIcon = {
        Icon(
            imageVector = icon,
            contentDescription = "contentDescription",
        )
    }
)

Then the dropdown dialog:

DropdownMenu(
    expanded = expanded,
    onDismissRequest = { expanded = false },
    modifier = Modifier.width(with(LocalDensity.current) { textFieldSize.width.toDp() })
) {
    options.forEach { label ->
        DropdownMenuItem(
            onClick = {
                fieldState.change(label) // Update the state on option click
                expanded = false // Close the dropdown dialog
            }
        ) {
            Text(text = label)
        }
    }
}

Output:

screen_recording_dropdown.mov

For multiple selection of items in the dropdown, use the SelectState instead.

@LinusMuema
Copy link
Collaborator

Closing this issue due and marking as resolved

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants