Skip to content

[Feat]: allow for optional fields #14

@RachelYoung94

Description

@RachelYoung94

My suggestion

z.string().optional()

having to get around it by doing:

import type { AutoFormConfig } from '#build/runtime/types/nuxt-auto-form'

const getComponent = (
  params: { key: string; state: any; zodType: any; config: AutoFormConfig },
  typeKey: string
) => {
  const { config, key } = params
  const component = config.components?.[typeKey]
  if (!component) {
    // just a polite warning for developer to create a custom slot to replace the div returned
    console.warn(`Unsupported Zod type: ${typeKey}, create a auto-form slot for the ${key} field.`)
    return {
      component: 'div'
    }
  }
  return component(params)
}

export default defineNuxtPlugin((_) => {
  updateAppConfig({
    autoForm: {
      components: {
        optional: ({ key, state, zodType, config }) => {
          // support for optional
          const innerType = zodType.def.innerType.type
          return getComponent({ key, zodType, config, state }, innerType)
        },
        custom: ({ key, state, zodType, config }) => {
          // support for custom fields
          return getComponent({ key, zodType, config, state }, zodType)
        }
      },
      submit: {
        props: {
          class: 'w-full flex justify-center'
        }
      }
    }
  })
})

but would be great if the component type was detected inside of the optional field

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions