modular-forms icon indicating copy to clipboard operation
modular-forms copied to clipboard

formAction$: extract special fields from zod schema

Open wmertens opened this issue 2 years ago • 4 comments

If there's a zod schema, it might be possible to use it to know what the field names are of the arrays, booleans etc, so that they don't need to be filled in as options to formAction$ and the form works without js out of the box.

Maybe the function can accept a zod option, which would be used for the validate function as well as extracting the special fields. That way it's optional behavior, only applying to zod schemas.

wmertens avatar Apr 24 '23 20:04 wmertens

Can you make a code example for the zod option? Do you know if it is technically possible to get this data from a zod schema? Without looking it up, I wouldn't know how to do that at the moment, but I could imagine that it is possible.

fabian-hiller avatar Apr 24 '23 20:04 fabian-hiller

I cannot take credit for this code, ChatGPT wrote it but it looks very plausible :)

import * as z from 'zod';

function getFieldsByType(schema: z.ZodSchema<any>, type: z.ZodTypeAny): string[] {
  const fields: string[] = [];

  // Get all fields of the schema
  const schemaFields = schema.shape;

  // Iterate through each field and check if it matches the specified type
  for (const fieldName in schemaFields) {
    const fieldSchema = schemaFields[fieldName];

    // Check if the field matches the specified type
    if (fieldSchema._def.type === type._def.type) {
      fields.push(fieldName);
    }
  }

  return fields;
}

example use:

const schema = z.object({
  name: z.string(),
  age: z.number(),
  isActive: z.boolean(),
  email: z.string().email(),
});

const booleanFields = getFieldsByType(schema, z.boolean());
console.log(booleanFields); // Output: ['isActive']

wmertens avatar Apr 24 '23 22:04 wmertens

Thanks for the code. As soon as I have some more time I will think about the API design.

fabian-hiller avatar Apr 25 '23 10:04 fabian-hiller

I have now investigated it and it seems to be possible to extract the required information with .shape and ._type. Since I don't have much time at the moment and this feature is not mandatory, I'll wait with the implementation. Feel free to leave a 👍 if you want to see this feature in Modular Forms. If a few thumbs come together, I'll try to make time for it.

fabian-hiller avatar May 07 '23 16:05 fabian-hiller