Merge pull request #1083 from Hexastack/1018-bug---content-type-fields-edit-form-fields-name-do-not-reflect-db-names
Some checks are pending
Build and Push Docker API Image / build-and-push (push) Waiting to run
Build and Push Docker Base Image / build-and-push (push) Waiting to run
Build and Push Docker UI Image / build-and-push (push) Waiting to run

fix: support contentType default name value
This commit is contained in:
Med Marrouchi
2025-06-11 14:13:11 +01:00
committed by GitHub
8 changed files with 157 additions and 89 deletions

View File

@@ -0,0 +1,23 @@
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { registerDecorator, ValidationOptions } from 'class-validator';
import { UniqueFieldNamesConstraint } from '../validators/validate-unique-names.validator';
export function UniqueFieldNames(validationOptions?: ValidationOptions) {
return function (object: Record<string, any>, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName,
options: validationOptions,
constraints: [],
validator: UniqueFieldNamesConstraint,
});
};
}

View File

@@ -14,7 +14,6 @@ import {
IsNotEmpty,
IsOptional,
IsString,
Matches,
Validate,
ValidateNested,
} from 'class-validator';
@@ -22,12 +21,12 @@ import {
import { FieldType } from '@/setting/schemas/types';
import { DtoConfig } from '@/utils/types/dto.types';
import { UniqueFieldNames } from '../decorators/unique-field-names.decorator';
import { ValidateRequiredFields } from '../validators/validate-required-fields.validator';
export class ContentField {
@IsString()
@IsNotEmpty()
@Matches(/^[a-z][a-z_0-9]*$/)
name: string;
@IsString()
@@ -58,6 +57,7 @@ export class ContentTypeCreateDto {
@ValidateNested({ each: true })
@Validate(ValidateRequiredFields)
@Type(() => ContentField)
@UniqueFieldNames()
fields?: ContentField[];
}

View File

@@ -7,13 +7,13 @@
*/
import { ModelDefinition, Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose from 'mongoose';
import { FieldType } from '@/setting/schemas/types';
import { BaseSchema } from '@/utils/generics/base-schema';
import { LifecycleHookManager } from '@/utils/generics/lifecycle-hook-manager';
import { ContentField } from '../dto/contentType.dto';
import { validateUniqueFields } from '../utilities/field-validation.utils';
@Schema({ timestamps: true })
export class ContentType extends BaseSchema {
@@ -28,7 +28,7 @@ export class ContentType extends BaseSchema {
*/
@Prop({
type: mongoose.Schema.Types.Mixed,
type: [ContentField],
default: [
{
name: 'title',
@@ -41,6 +41,19 @@ export class ContentType extends BaseSchema {
type: FieldType.checkbox,
},
],
required: true,
validate: {
/**
* Ensures every `label` in the fields array is unique.
* Runs on `save`, `create`, `insertMany`, and `findOneAndUpdate`
* when `runValidators: true` is set.
*/
validator(fields: ContentField[]): boolean {
return validateUniqueFields(fields, 'label');
},
message:
'Each element in "fields" must have a unique "label" (duplicate detected)',
},
})
fields: ContentField[];
}

View File

@@ -0,0 +1,13 @@
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
export const validateUniqueFields = <T>(
fields: T[],
fieldName: keyof T,
): boolean =>
new Set(fields.map((f) => f[fieldName] as string)).size === fields.length;

View File

@@ -0,0 +1,29 @@
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import {
ValidationArguments,
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import { ContentField } from '../dto/contentType.dto';
import { validateUniqueFields } from '../utilities/field-validation.utils';
@ValidatorConstraint({ async: false })
export class UniqueFieldNamesConstraint
implements ValidatorConstraintInterface
{
validate(fields: ContentField[], _args: ValidationArguments) {
return validateUniqueFields(fields, 'label');
}
defaultMessage(args: ValidationArguments) {
return `${args.property} contains duplicate "label" values; each field.name must be unique`;
}
}

View File

@@ -64,7 +64,7 @@ const contentTypes: TContentTypeFixtures['values'][] = [
},
{
name: 'subtitle',
label: 'Image',
label: 'Subtitle',
type: FieldType.file,
},
],

View File

@@ -8,7 +8,7 @@
import AddIcon from "@mui/icons-material/Add";
import { Button } from "@mui/material";
import { FC, Fragment, useEffect } from "react";
import { FC, Fragment } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { ContentContainer, ContentItem } from "@/app-components/dialogs";
@@ -19,10 +19,14 @@ import { useToast } from "@/hooks/useToast";
import { useTranslate } from "@/hooks/useTranslate";
import { EntityType } from "@/services/types";
import { ComponentFormProps } from "@/types/common/dialogs.types";
import { ContentFieldType, IContentType } from "@/types/content-type.types";
import {
ContentFieldType,
IContentType,
IContentTypeAttributes,
} from "@/types/content-type.types";
import { FieldInput } from "./components/FieldInput";
import { FIELDS_FORM_DEFAULT_VALUES, READ_ONLY_FIELDS } from "./constants";
import { FIELDS_FORM_DEFAULT_VALUES } from "./constants";
export const ContentTypeForm: FC<ComponentFormProps<IContentType>> = ({
data: { defaultValues: contentType },
@@ -33,20 +37,36 @@ export const ContentTypeForm: FC<ComponentFormProps<IContentType>> = ({
const { toast } = useToast();
const { t } = useTranslate();
const {
reset,
control,
register,
setValue,
formState: { errors },
handleSubmit,
} = useForm<Partial<IContentType>>({
defaultValues: {
name: contentType?.name || "",
fields: contentType?.fields || FIELDS_FORM_DEFAULT_VALUES,
},
} = useForm<IContentType>({
defaultValues: contentType
? { name: contentType.name, fields: contentType.fields }
: {
name: "",
fields: FIELDS_FORM_DEFAULT_VALUES,
},
});
const { append, fields, remove } = useFieldArray({
name: "fields",
rules: {
validate: (fields) => {
const hasUniqueLabels =
new Set(fields.map((f) => f["label"] as string)).size ===
fields.length;
if (!hasUniqueLabels) {
toast.error(t("message.duplicate_labels_not_allowed"));
return false;
}
return true;
},
},
control,
});
const options = {
@@ -67,44 +87,14 @@ export const ContentTypeForm: FC<ComponentFormProps<IContentType>> = ({
EntityType.CONTENT_TYPE,
options,
);
const onSubmitForm = (params) => {
const labelCounts: Record<string, number> = params.fields.reduce(
(acc, field) => {
if (!field.label.trim()) return acc;
acc[field.label] = (acc[field.label] || 0) + 1;
return acc;
},
{} as Record<string, number>,
);
const hasDuplicates = Object.values(labelCounts).some(
(count: number) => count > 1,
);
if (hasDuplicates) {
toast.error(t("message.duplicate_labels_not_allowed"));
return;
}
if (contentType) {
const onSubmitForm = (params: IContentTypeAttributes) => {
if (contentType?.id) {
updateContentType({ id: contentType.id, params });
} else {
createContentType(params);
}
};
useEffect(() => {
if (contentType) {
reset({
name: contentType.name,
fields: contentType.fields || FIELDS_FORM_DEFAULT_VALUES,
});
} else {
reset({ name: "", fields: FIELDS_FORM_DEFAULT_VALUES });
}
}, [contentType, reset]);
return (
<Wrapper onSubmit={handleSubmit(onSubmitForm)} {...WrapperProps}>
<form onSubmit={handleSubmit(onSubmitForm)}>
@@ -121,20 +111,19 @@ export const ContentTypeForm: FC<ComponentFormProps<IContentType>> = ({
autoFocus
/>
</ContentItem>
{fields.map((f, index) => (
{fields.map((field, idx) => (
<ContentItem
key={f.id}
key={field.id}
display="flex"
justifyContent="space-between"
gap={2}
>
<FieldInput
setValue={setValue}
control={control}
idx={idx}
name={field.name}
remove={remove}
index={index}
disabled={READ_ONLY_FIELDS.includes(f.label as any)}
control={control}
setValue={setValue}
/>
</ContentItem>
))}
@@ -143,7 +132,11 @@ export const ContentTypeForm: FC<ComponentFormProps<IContentType>> = ({
startIcon={<AddIcon />}
variant="contained"
onClick={() =>
append({ label: "", name: "", type: ContentFieldType.TEXT })
append({
label: "",
name: "",
type: ContentFieldType.TEXT,
})
}
>
{t("button.add")}

View File

@@ -8,14 +8,8 @@
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import { MenuItem } from "@mui/material";
import { useEffect } from "react";
import {
Control,
Controller,
UseFieldArrayRemove,
UseFormSetValue,
useWatch,
} from "react-hook-form";
import { useMemo } from "react";
import { Control, Controller, UseFormSetValue } from "react-hook-form";
import { IconButton } from "@/app-components/buttons/IconButton";
import { Input } from "@/app-components/inputs/Input";
@@ -23,26 +17,23 @@ import { useTranslate } from "@/hooks/useTranslate";
import { ContentFieldType, IContentType } from "@/types/content-type.types";
import { slugify } from "@/utils/string";
import { READ_ONLY_FIELDS } from "../constants";
export const FieldInput = ({
idx,
name,
remove,
control,
setValue,
index,
...props
}: {
index: number;
disabled?: boolean;
remove: UseFieldArrayRemove;
control: Control<Partial<IContentType>>;
setValue: UseFormSetValue<Partial<IContentType>>;
idx: number;
name: string;
remove: (index?: number | number[]) => void;
control: Control<IContentType>;
setValue: UseFormSetValue<IContentType>;
}) => {
const { t } = useTranslate();
const label = useWatch({
control: props.control,
name: `fields.${index}.label`,
});
useEffect(() => {
setValue(`fields.${index}.name`, label ? slugify(label) : "");
}, [label, setValue, index]);
const isDisabled = useMemo(() => idx < READ_ONLY_FIELDS.length, [idx]);
return (
<>
@@ -50,40 +41,46 @@ export const FieldInput = ({
variant="text"
color="error"
size="medium"
onClick={() => props.remove(index)}
disabled={props.disabled}
onClick={() => remove(idx)}
disabled={isDisabled}
>
<DeleteOutlineIcon strokeWidth={1} fontSize="medium" />
</IconButton>
<Controller
control={props.control}
name={`fields.${index}.label`}
control={control}
name={`fields.${idx}.label`}
rules={{ required: t("message.label_is_required") }}
render={({ field, fieldState }) => (
<Input
disabled={props.disabled}
disabled={isDisabled}
{...field}
label={t("label.label")}
error={!!fieldState.error}
helperText={fieldState.error?.message}
onChange={(e) => {
const value = e.target.value;
if (!name) {
setValue(`fields.${idx}.name`, value ? slugify(value) : "");
}
field.onChange(e);
}}
/>
)}
/>
<Controller
name={`fields.${index}.name`}
name={`fields.${idx}.name`}
render={({ field }) => (
<Input disabled {...field} label={t("label.name")} />
)}
control={props.control}
control={control}
/>
<Controller
name={`fields.${index}.type`}
control={props.control}
name={`fields.${idx}.type`}
control={control}
render={({ field }) => (
<Input
disabled={props.disabled}
disabled={isDisabled}
label={t("label.type")}
{...field}
select