budibase/packages/standard-components/src/forms/OptionsField.svelte

99 lines
2.3 KiB
Svelte
Raw Normal View History

<script>
import { CoreSelect, RadioGroup } from "@budibase/bbui"
import Field from "./Field.svelte"
export let field
export let label
export let placeholder
export let disabled = false
export let optionsType = "select"
2021-08-04 15:33:51 +02:00
export let defaultValue
export let optionsSource = "schema"
export let dataProvider
export let labelColumn
export let valueColumn
export let customOptions
let fieldState
let fieldApi
let fieldSchema
$: flatOptions = optionsSource == null || optionsSource === "schema"
$: options = getOptions(
optionsSource,
fieldSchema,
dataProvider,
labelColumn,
valueColumn
)
const getOptions = (
optionsSource,
fieldSchema,
dataProvider,
labelColumn,
valueColumn
) => {
// Take options from schema
if (optionsSource == null || optionsSource === "schema") {
return fieldSchema?.constraints?.inclusion ?? []
}
// Extract options from data provider
if (optionsSource === "provider" && valueColumn) {
let optionsSet = {}
dataProvider?.rows?.forEach(row => {
const value = row?.[valueColumn]
if (value) {
const label = row[labelColumn] || value
optionsSet[value] = { value, label }
}
})
return Object.values(optionsSet)
}
// Extract custom options
if (optionsSource === "custom" && customOptions) {
return customOptions
}
return []
}
</script>
<Field
{field}
{label}
{disabled}
2021-08-04 15:33:51 +02:00
{defaultValue}
type="options"
bind:fieldState
bind:fieldApi
bind:fieldSchema
>
{#if fieldState}
2021-08-03 21:34:26 +02:00
{#if optionsType === "select"}
<CoreSelect
value={$fieldState.value}
id={$fieldState.fieldId}
disabled={$fieldState.disabled}
error={$fieldState.error}
{options}
{placeholder}
on:change={e => fieldApi.setValue(e.detail)}
getOptionLabel={flatOptions ? x => x : x => x.label}
getOptionValue={flatOptions ? x => x : x => x.value}
/>
2021-08-03 21:34:26 +02:00
{:else if optionsType === "radio"}
<RadioGroup
value={$fieldState.value}
id={$fieldState.fieldId}
disabled={$fieldState.disabled}
error={$fieldState.error}
options={fieldSchema?.constraints?.inclusion ?? []}
on:change={e => fieldApi.setValue(e.detail)}
/>
{/if}
{/if}
</Field>