Dynamic enum

Hi all,

I’m using the react flavour of json forms and currently using the material renderers. I’d love to be able to have a drop down in my form where the enumerations are populated using values from my elsewhere in my data.

i’ve seen that ajv has $data reference that can be used in enum that seems to be what I want from a validation perspective however I believe that this $data reference is not supported in the Json4 or Json7 meta schemas that json forms supports.

has anybody done something like this or got any pointers?

apologies if my terminology is a bit off, i’m quite new to all this.

[original thread by James Morris]

[Benjamin Börngen-Schmidt]

Hey James,

in the i18n example jsonforms/util.tsx at master · eclipsesource/jsonforms · GitHub the values of the labels are overwritten. I guess you could do the same with the enum values, before you pass the schema to JsonForms.

Hi @james-morris(james-morris), you’re right, I don’t think there is any way to express this with JSON Schema. We support the $data reference in JSON Forms via Ajv: when it’s only used for validation then it will also work for JSON Forms when you hand in a properly configured Ajv.

At the moment you can handle them via a custom renderer or exchanging the JSON Schema whenever you calculate a new set of enums. I elaborated on this in this question. Please let me know if you have further questions.

[James Morris]

Hi @sdirix(sdirix) thanks for all your help so far!

I think i’ve managed to get the enum: {$data: …} propertly configured in my schema and have set $data = true in my ajv however when I try to use the schema in JsonForms I get the following error:

‘Type ‘{ type: string; enum: { $data: string; }; }’ is not assignable to type ‘JsonSchema7’. Types of property ‘enum’ are incompatible.’

Is this something I can fix or am I not going in the direction you initially suggested?

This type error can be “fixed” by casting your schema to any. However you might be running into issues. As you use the $data not only for validation but to also as a part of the schema structure we check for our renderers. For example the enum renderer will try to look into the enum array, but will find an object containing $data instead. I could imagine that the enum renderer will therefore not work.

[James Morris]

Can I get round that by adding a custom renderer that is used in place of the traditional enum renderer in the case where the enum isn’t an array, where enum: {$data: …}?

Yes definitely. Using a custom renderer you can cover any structure you want. In theory the schema doesn’t even need to be a JSON Schema then. The only real constraint from JSON Forms core is that AJV can handle your schema (or you disable validation completely). In your case that should be of no concern.