Loving Tina? us on GitHub0.0k
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: TinaCMS
form: 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 = `#graphql
query ($filter: PageFilter) {
pageConnection(filter: $filter) {
edges {
node {
... on Document {
_sys {
path
}
}
}
}
}
}
`
export default defineConfig({
schema: {
collections: [
{
ui: {
beforeSubmit: async ({
form,
cms,
values,
}: {
form: Form
cms: TinaCMS
values: Record<string, any>
}) => {
const slug = (values.slug ?? '').toString().trim().toLowerCase()
if (!slug) return values
const tinaAPI = (cms as TinaCMS).api?.tina
const { data } = await tinaAPI?.request(slugCheckQuery, {
variables: { filter: { slug: { eq: slug } } },
})
const currentId = form.id
const 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 beforeSubmit
beforeSubmit: async ({
form,
cms,
values,
}: {
form: Form
cms: TinaCMS
values: 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: Form
cms: TinaCMS
values: 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: Form
cms: TinaCMS
values: Record<string, any>
}) => {
return {
...values,
slug: values.title
.toLowerCase()
.replace(/ /g, '-')
.replace(/[^\w-]+/g, ''),
}
},
//...
},
//...
},
//...
],
},
//...
})