kettanaito/react-advanced-form

Question : How to handle multiple values ?

Gus19 opened this issue · 1 comments

Gus19 commented

Hello,

I have a form with :

  • a radio list
  • a checkboxes list

I found the components for a single radio/checkbox (and they work well) but I don't figure how to wrap this components into a parent.

Could you help me ?

Ideally, I would like to get the following json :

{
  radio: ID10,
  chekboxes: [
    ID20,
    ID21,
    ID22
  ]
}

By the way I don't understand either for the select, I set the multiple attribute but only one value is selected in the end (but I don't plan to use this one for the moment).

Thanks !

There's very little value in composing those values on the component level. Consider composing them on the serialization level instead. This means having 1 radio list and 1 checkboxes list as separate fields, and then transforming them to your liking when serializing the form in the onSerialize prop of the Form.

If you really need a complex field as you've described, you can do it via the createField function. It supports custom options to map and serialize complex fields. Here's an example that implements a BirthDate field that composes 3 standalone inputs:

export default createField({
/**
* Allow multiple instances of a field with the same name
* because "birthDate" contains three children input fields.
*/
allowMultiple: true,
valuePropName: 'date',
/**
* Modifies the field's state to include custom type.
* This prevents children inputs to listen to "type: text"
* validation rules.
*/
mapPropsToField: ({ fieldRecord }) => ({
...fieldRecord,
type: 'birthDate',
}),
enforceProps: () => ({
type: 'text',
}),
/**
* Execute mapping function each time a "raw" value ("1999-12-10")
* comes into the field. Has no effect over internal field value handling.
*/
mapValue(value) {
const parsedDate = value.split('-')
return {
year: parsedDate[0] || '',
month: parsedDate[1] || '',
day: parsedDate[2] || '',
}
},
/**
* A predicate function that describes when the field has value.
* Useful for the fields with complex internal value instance,
* like this one, where the value is stored as an Object.
*/
assertValue(date) {
return date.year || date.month || date.day
},
/**
* Custom serialization function that executes upon the
* field's serialization. Joins Object values into a string.
*/
serialize(date) {
return [date.year, date.month, date.day].join('-')
},
})(BirthDate)