Required Field Array

Hi All,

I am having an issue with a required array. The required error will show on load, but if you add a row, the error will go away which makes sense. However, once you delete that row, the required error does not reappear.

@sdirix, is this a JSON Forms bug? Do you have any ideas for a quick fix?

Thanks,
Abby

Hi @avwchapman,

This very likely not a bug. The required validation just checks whether an array exists. When the first element is added via JSON Forms, any necessary parent elements like the array will be added too.

However using the standard interactions of JSON Forms, removing the entries of the array will not delete the array itself, so you will be left with an empty array. Therefore the required erros does not come back.

If you just need some validation, then you can add a minItems prop and set it to 1. In that case you will have a different error shown. If you require the array to be deleted when the last element is removed then you can either:

  • use a custom array renderer which does exactly that when the last element is removed. You should be able to just reuse the existing one and just need to overwrite the remove items logic, or
  • you listen to the data changes outside of JSON Forms and set the array to undefined once it’s empty. Just make sure that the root data object also changes as otherwise JSON Forms will not recognize that you modified the data, or
  • you wait for the upcoming middleware support. Similar to the previous solution you can then manually delete the array when needed, it will however be more easily to implement and more performant.

Thank you for the response!

I am getting an error saying that array is not defined.

const removeItems = (path, toDelete) => { Dispatch( update(path, array => { toDelete .sort() .reverse() .array.forEach(element => { array.splice(element, 1); }); }) ); return array; };

Update (now I am getting an invalid hook error):

const removeItems = (path, toDelete) => { const core = useJsonForms(); const dispatch = core.dispatch; dispatch( Actions.update(path, array => { toDelete .sort() .reverse() .array.forEach(element => { array.splice(element, 1); }); return array; }) ); };

@sdirix any ideas?

Hi @avwchapman,

useJsonForms is a custom React hook, so you need to follow the rules of hooks, i.e. use them unconditionally at top level of your component.