select.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type {
  3. FormFieldAdditionalProps,
  4. FormSchemaField,
  5. } from '#shared/components/Form/types.ts'
  6. import type {
  7. FieldResolverModule,
  8. ObjectAttributeSelectOptions,
  9. } from '#shared/entities/object-attributes/types/resolver.ts'
  10. import { camelize } from '#shared/utils/formatter.ts'
  11. import FieldResolver from '../FieldResolver.ts'
  12. export type ObjectSelectValue = string | number | boolean
  13. export interface ObjectSelectOption {
  14. label?: string
  15. disabled?: boolean
  16. value: ObjectSelectValue
  17. }
  18. export class FieldResolverSelect extends FieldResolver {
  19. fieldType = 'select'
  20. protected multiFieldAttributeType = 'multiselect'
  21. public fieldTypeAttributes() {
  22. const attributes: Partial<FormSchemaField> = {}
  23. const props: FormFieldAdditionalProps = {
  24. noOptionsLabelTranslation: !this.attributeConfig.translate,
  25. clearable: !!this.attributeConfig.nulloption,
  26. options: [],
  27. historicalOptions: this.attributeConfig.historical_options,
  28. }
  29. if (this.attributeConfig.relation) {
  30. attributes.relation = {
  31. type: this.attributeConfig.relation as string,
  32. }
  33. if (this.attributeConfig.filter) {
  34. attributes.relation.filterIds = this.attributeConfig.filter as number[]
  35. }
  36. props.belongsToObjectField = camelize(
  37. (this.attributeConfig.belongs_to as string) || '',
  38. )
  39. props.sorting = 'label'
  40. } else if (this.attributeConfig.options) {
  41. props.options = this.mappedOptions()
  42. }
  43. if (this.attributeType === this.multiFieldAttributeType)
  44. props.multiple = true
  45. return {
  46. ...attributes,
  47. props,
  48. }
  49. }
  50. protected mappedOptions(): ObjectSelectOption[] {
  51. const options = this.attributeConfig.options as ObjectAttributeSelectOptions
  52. if (Array.isArray(options)) {
  53. return options.map(({ name, value }) => ({
  54. label: name,
  55. value,
  56. }))
  57. }
  58. return Object.keys(options).map((key) => ({
  59. label: key,
  60. value: options[key],
  61. }))
  62. }
  63. }
  64. export default <FieldResolverModule>{
  65. type: 'select',
  66. resolver: FieldResolverSelect,
  67. }