checkbox-set.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import Field from './_field';
  2. import CheckBox from 'app/ui/atoms/checkbox';
  3. import { View, Row } from 'app/design/view'
  4. import { appSetting } from 'app/lib/util';
  5. import { useFormField } from 'app/lib/form/use-form-field';
  6. import { stringArrayInitialValue } from 'app/lib/form/field-initial-values';
  7. const themeSettings = appSetting('theme', 'checkbox_set');
  8. export default function FormFieldCheckboxSet(props) {
  9. const df = stringArrayInitialValue(props.value);
  10. const { field } = useFormField(props, {
  11. defaultValue: df,
  12. syncValue: false,
  13. });
  14. const selected = Array.isArray(field.value) ? field.value : df;
  15. const setSelection = (val) => {
  16. const id = String(val);
  17. field.onChange(
  18. selected.includes(id)
  19. ? selected.filter((item) => item !== id)
  20. : [...selected, id]
  21. );
  22. };
  23. const values = Array.isArray(props.values)
  24. ? props.values.map((obj) => ({ id: obj.key, label: obj.value }))
  25. : Object.entries(props.values).map(([key, value]) => ({ id: key, label: value }));
  26. return (
  27. <Field {...props}>
  28. <View className={`${props.view != 'column' ? 'flex-row justity-center' : 'items-start'} ${themeSettings.container} flex-wrap`}>
  29. {values.map((item2, index) => {
  30. const checked = selected.includes(String(item2.id));
  31. return (
  32. <Row className="items-center flex-wrap w-full" key={'chk' + index}>
  33. <CheckBox
  34. value={checked}
  35. status={checked ? 'checked' : 'unchecked'}
  36. onPress={() => setSelection(item2.id)}
  37. title={item2.label}
  38. />
  39. </Row>
  40. );
  41. })}
  42. </View>
  43. </Field>
  44. );
  45. }