Skip to content

Add setSchema() to support dynamic schemas #216

Description

@jith51

Motivation

It would be very useful for Formisch to provide a way to dynamically replace the schema of an existing FormStore.

This is especially important for forms representing objects whose validation rules depend on external data or whose fields are dynamically defined.

For example, a form may contain custom attributes whose definition comes from a parent object:

{
  name: string,
  customAttributesDefinition: [
    {
      name: string,
      label: string,
      type: string
    }
  ]
}

The validation schema may therefore need to change when the parent object changes.

Current limitation

Currently, the schema is provided when the form is created:

const form = useForm({
  schema,
})

If the schema needs to change later, there does not appear to be a way to update it on an existing FormStore.

Using reset() does not solve this problem because it resets the form state and input, but does not replace the schema.

A workaround in Vue is to recreate the form/component, for example using a changing :key, but this also recreates the entire FormStore and is not ideal.

Proposed API

Add a setSchema() method:

setSchema(form, newSchema)

For example:

const schema = createSchema(parentAttributes)

setSchema(form, schema)

The method would replace the schema associated with the existing FormStore.

Expected behavior

When setSchema() is called, Formisch should:

  1. Replace the current schema with the new schema.
  2. Keep the existing form input and values.
  3. Keep the existing FormStore instance.
  4. Update the field validation structure according to the new schema.
  5. Revalidate fields according to the configured validation strategy.
  6. Update isValid and the associated errors accordingly.

For example:

const form = useForm({
  schema: initialSchema,
  validate: 'blur',
  revalidate: 'input',
})

// External data changes

const newSchema = createSchema(newParentAttributes)

setSchema(form, newSchema)

The form would then continue using the same FormStore, but with the new validation rules.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

questionFurther information is requested

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions