react-admin icon indicating copy to clipboard operation
react-admin copied to clipboard

Add index to FormDataConsumer when used inside an ArrayInput

Open dalen opened this issue 10 months ago • 2 comments

Is your feature request related to a problem? Please describe.

When writing some types of field level validators for fields inside an ArrayInput it would be useful to be able to get the index of the current component in some way. But I can also imagine other use cases for it.

Describe the solution you'd like

FormDataConsumer exposes formData & scopedFormData. I would like it to also expose index

Describe alternatives you've considered

Additional context

dalen avatar Feb 06 '25 11:02 dalen

This is not properly documented but there is a useSimpleFormIteratorItem hook that returns the index as you can see in the <SimpleFormIterator> documentation.

However, this implies to create a component which FormDataConsumer was actually meant to avoid. Can you open a PR for this targeting the next branch?

djhi avatar Feb 11 '25 09:02 djhi

@djhi I am also interested in having the index somehow, as I need it for onChange cases.

Use Case: I want on onChange of an input that is inside an ArrayInput to be able to change the value of a sibling input that is in the same scopedFormData (i.e. in the same index on the ArrayInput). I do not find a way to do this using the formMethods of react-hook-form as I do not have the index to know which one to change, I do not have the path of the object.

I need to do something like that, to change the sibling url input on the onChange of a title input:

    formMethods.setValue(`${path}url`, null, {
      shouldDirty: true,
      shouldTouch: true,
    }) 

but, how can someone get this path? (i.e. the index of the current "record item" of the ArrayInput?

I cannot use a hook there, inside the onChange callback, so IF index or path was also exposed on onChange that would be great!

I believe it would be very useful to expose the path and/or the index of the item. (the index is OK, but the total form's field path is also needed, as there may be nested-of-nested-of-nested ArrayInput fields...)

Thanks a lot!

afilp avatar Feb 20 '25 08:02 afilp