v.Latest
Documentation
Before Submit Function
Loading last updated info...
On This Page
The before submit function allows you to run a function on the frontend before the form is submitted to the backend and optionally modify the values of a document.
Definition
import { TinaCMS, Form } from 'tinacms'type BeforeSubmitFunction = (args: {values: Record<string, unknown>cms: TinaCMSform: Form}) => Promise<void | Record<string, unknown>>
Querying content
Content can be queried from within beforeSubmit using the cms argument. The generated client is not available in the config, so queries are made by passing a raw GraphQL query string to cms.api.tina.request().
// tina/config.{ts,js}const slugCheckQuery = `#graphqlquery ($filter: PageFilter) {pageConnection(filter: $filter) {edges {node {... on Document {_sys {path}}}}}}`export default defineConfig({schema: {collections: [{ui: {beforeSubmit: async ({form,cms,values,}: {form: Formcms: TinaCMSvalues: Record<string, any>}) => {const slug = (values.slug ?? '').toString().trim().toLowerCase()if (!slug) return valuesconst tinaAPI = (cms as TinaCMS).api?.tinaconst { data } = await tinaAPI?.request(slugCheckQuery, {variables: { filter: { slug: { eq: slug } } },})const currentId = form.idconst conflict = data?.pageConnection?.edges?.find((edge) => edge?.node?._sys?.path !== currentId)if (conflict) {throw new Error(`The slug "${slug}" is already used by another page.`)}return values},//...},//...},//...],},//...})
Examples
Adding a last updated field
// tina/config.{ts.js}export default defineConfig({schema: {collections: [{ui: {// Example of beforeSubmitbeforeSubmit: async ({form,cms,values,}: {form: Formcms: TinaCMSvalues: Record<string, any>}) => {return {...values,lastUpdated: new Date().toISOString(),}},//...},//...},//...],},//...})
Adding a created at field
export default defineConfig({schema: {collections: [{ui: {beforeSubmit: async ({form,cms,values,}: {form: Formcms: TinaCMSvalues: Record<string, any>}) => {if (form.crudType === 'create') {return {...values,createdAt: new Date().toISOString(),}}},//...},//...},//...],},//...})
Adding a slug field
export default defineConfig({schema: {collections: [{ui: {beforeSubmit: async ({form,cms,values,}: {form: Formcms: TinaCMSvalues: Record<string, any>}) => {return {...values,slug: values.title.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, ''),}},//...},//...},//...],},//...})