fix(richtext-lexical): Blocks: do not include empty arrays in form state (#5526)

This commit is contained in:
Alessio Gravili
2024-03-28 15:40:02 -04:00
committed by GitHub
parent 5eaf00ba0e
commit cfdc941207
3 changed files with 24 additions and 2 deletions

View File

@@ -6,6 +6,8 @@ import { useAllFormFields } from '@payloadcms/ui/forms/Form'
import { reduceFieldsToValues } from '@payloadcms/ui/utilities/reduceFieldsToValues'
import { useEffect } from 'react'
import { removeEmptyArrayValues } from './removeEmptyArrayValues.js'
type Props = {
onChange?: ({
fullFieldsWithValues,
@@ -19,7 +21,9 @@ type Props = {
export const FormSavePlugin: React.FC<Props> = (props) => {
const { onChange } = props
const [fields, dispatchFields] = useAllFormFields()
const [_fields] = useAllFormFields()
const fields = removeEmptyArrayValues({ fields: _fields })
// Pass in fields, and indicate if you'd like to "unflatten" field data.
// The result below will reflect the data stored in the form at the given time

View File

@@ -24,6 +24,7 @@ import type { BlocksFeatureClientProps } from '../feature.client.js'
import { useEditorConfigContext } from '../../../lexical/config/client/EditorConfigProvider.js'
import { BlockContent } from './BlockContent.js'
import './index.scss'
import { removeEmptyArrayValues } from './removeEmptyArrayValues.js'
type Props = {
blockFieldWrapperName: string
@@ -75,7 +76,7 @@ export const BlockComponent: React.FC<Props> = (props) => {
if (state) {
setInitialState({
...state,
...removeEmptyArrayValues({ fields: state }),
blockName: {
initialValue: '',
passesCondition: true,

View File

@@ -0,0 +1,17 @@
import type { FormState } from 'payload/types'
/**
* By default, if an array field is empty, it will be included in the form state with a value of 0.
* We do not need this behavior here, By setting `disableFormData` to true, we can prevent the field from being included in the form state
* like that.
* @param fields form state
*/
export function removeEmptyArrayValues({ fields }: { fields: FormState }): FormState {
for (const key in fields) {
const field = fields[key]
if (Array.isArray(field.rows) && 'value' in field) {
field.disableFormData = true
}
}
return fields
}