v4
Documentation
API
Model configuration

Model configuration

💡

This documentation covers an older version of Next Admin. If you are using the latest version (>=5.0.0 and above), please refer to the current documentation.

To configure your models, you can use the model property of the NextAdmin options parameter.

This property allows you to configure everything about how your models, their fields, their relations are displayed and edited.

Example for a schema with a User, Post and Category model:

import { NextAdminOptions } from "@premieroctet/next-admin";
 
export const options: NextAdminOptions = {
  /* Your other options here */
  model: {
    User: {
      toString: (user) => `${user.name} (${user.email})`,
      title: "Users",
      icon: "UsersIcon",
      list: {
        display: ["id", "name", "email", "posts", "role", "birthDate"],
        search: ["name", "email"],
        filters: [
          {
            name: "is Admin",
            active: false,
            value: {
              role: {
                equals: "ADMIN",
              },
            },
          },
        ],
      },
      edit: {
        display: [
          "id",
          "name",
          "email",
          "posts",
          "role",
          "birthDate",
          "avatar",
        ],
      },
      actions: [
        {
          title: "Send email",
          action: async (model, ids) => {
            const response = await fetch("/api/email", {
              method: "POST",
              body: JSON.stringify(ids),
            });
 
            if (!response.ok) {
              throw new Error("Failed to send email");
            }
          },
          successMessage: "Email sent successfully",
          errorMessage: "Error while sending email",
        },
      ],
    },
    Post: {
      toString: (post) => `${post.title}`,
    },
    Category: {
      title: "Categories",
      icon: "InboxStackIcon",
      toString: (category) => `${category.name}`,
      list: {
        display: ["name", "posts"],
      },
      edit: {
        display: ["name", "posts"],
      },
    },
  },
};
 

model

It takes as key a model name of your schema as value an object to configure it.

By default if no models are defined, they will all be displayed in the admin. If you want more control, you have to define each model individually as empty objects or with the following properties:

NameTypeDescriptionDefault Value
toStringFunctiona function that is used to display your record in related listid field
aliasesObjectan object containing the aliases of the model fields as keys, and the field name-
titleStringa string used to display the model name in the sidebar and in the section titleModel name
listObjectan object containing the list options (see list property)-
editObjectan object containing the edit options (see edit property)-
actionsArray an array of actions (see actions property)-
iconStringthe outline HeroIcon (opens in a new tab) name displayed in the sidebar and pages title-
permissionsArrayan array to specify restricted permissions on model-

list property

This property determines how your data is displayed in the list view

NameTypeDescriptionDefault Value
searchArrayan array of searchable fieldsAll scalar fields are searchable by default
displayArrayan array of fields that are displayed in the listAll scalar fields are displayed by default
fieldsObjectan object containing the model fields as keys, and customization values (see fields property)-
copyArrayan array of fields that are copyable into the clipboardundefined - no field is copyable by default
defaultSortObjectan optional object to determine the default sort to apply on the list-
defaultSort.fieldStringthe model's field name to which the sort is applied. It is mandatory-
defaultSort.directionStringthe sort direction to apply. It is optional-
filtersArray define a set of Prisma filters that user can choose in list (see filters)-
exportsObjectan object or array of export - containing export url (see exports)-

The search property is only available for scalar fields (opens in a new tab).

list.filters property

The filters property allow you to define a set of Prisma filters (opens in a new tab) that users can apply on the list view. It's an array of the following object:

NameTypeDescriptionDefault Value
nameStringa unique name for the filter-
activeBooleana boolean to set the filter active by defaultfalse
valueStringa where clause Prisma filter of the related model (e.g. Prisma operators (opens in a new tab))-

list.exports property

The exports property allows you to define a set of export actions that users can apply on the list view. It's an object or an array of objects that can have the following properties:

NameTypeDescriptionDefault Value
formatStringa string defining the format of the export. It's used to label the export buttonundefined
urlStringa string defining the URL of the export actionundefined

The exports property does not account for active filters. If you want to export filtered data, you need to add the filters to the URL or in your export action.

edit property

This property determines how your data is displayed in the edit view

NameTypeDescriptionDefault Value
displayArray an array of fields that are displayed in the form. It can also be an object that will be displayed in the form of a notice (see notice)all scalar fields are displayed
stylesObjectan object containing the styles of the form (see styles) -
fieldsObjectan object containing the model fields as keys, and customization values (see fields property)-
submissionErrorMessageStringa message displayed if an error occurs during the form submission'Submission error'

edit.styles property

The styles property is available in the edit property.

⚠️

If your options are defined in a separate file, make sure to add the path to the content property of the tailwind.config.js file (see TailwindCSS configuration).

NameTypeDescription
_formStringa string defining the classname of the form
...Stringall fields of the model, with the field name as the key and the classname as the value

Here is an example of using styles property:

styles: {
  _form: "form-classname",
  ... // all fields
};

edit.fields & list.fields property

The fields property is available in both list and edit properties.

For the edit property, it can take the following:

NameTypeDescriptionDefault Value
validateFunctiona function that takes the field value as a parameter, and returns a boolean-
formatStringa string defining an OpenAPI field format, overriding the one set in the generator. An extra file format can be used to be able to have a file input-
inputReact Elementa React Element that should receive CustomInputProps. For App Router, this element must be a client component-
handlerObject-
handler.getFunctiona function that takes the field value as a parameter and returns a transformed value displayed in the form-
handler.uploadFunctionan async function that is used only for formats file and data-url. It takes a Buffer object and an information object containing name and type properties as parameters and must return a string. It can be useful to upload a file to a remote provider-
handler.uploadErrorMessageStringan optional string displayed in the input field as an error message in case of a failure during the upload handler-
optionFormatterFunctiononly for relation fields, a function that takes the field values as a parameter and returns a string. Useful to display your record in related list-
tooltipStringA tooltip content to display for the field -
helperTextStringa helper text that is displayed underneath the input-
disabledBooleana boolean to indicate that the field is read only-
displayString only for relation fields, indicate which display format to use between list, table or selectselect
requiredBooleana true value to force a field to be required in the form, note that if the field is required by the Prisma schema, you cannot set required to false-
relationOptionFormatterFunctionsame as optionFormatter, but used to format data that comes from an explicit many-to-many (opens in a new tab) relationship-
orderFieldStringthe field to use for relationship sorting. This allows to drag and drop the related records in the list display-
relationshipSearchFieldStringa field name of the explicit many-to-many relation table to apply the search on. See handling explicit many-to-many (opens in a new tab)-

actions property

The actions property is an array of objects that allows you to define a set of actions that can be executed on one or more records of the resource. On the list view, there is a default action for deletion. The object can have the following properties:

NameTypeDescription
titleStringaction title that will be shown in the action dropdown
actionFunctionan async function that will be triggered when selecting the action in the dropdown. For App Router, it must be defined as a server action
successMessageStringa message that will be displayed when the action is successful
errorMessageStringa message that will be displayed when the action fails

CustomInputProps type

Represents the props that are passed to the custom input component.

NameTypeDescription
nameStringthe field name
valueanythe field value
onChangeFunction a function taking a ChangeEvent (opens in a new tab) as a parameter
readonlyBooleanboolean indicating if the field is editable or not
rawErrorsArrayarray of strings containing the field errors
disabledBooleanboolean indicating if the field is disabled

NextAdmin Context type

Represents the context that is passed to the formatter function in the list.fields property.

NameTypeDescription
localeStringThe locale used by the calling page. (refers to the accept-language (opens in a new tab) header)
rowObjectThe current row of the list view

Notice type

This type represents the notice object that can be used in the edit property of a model. If you pass a Notice object in the display array, it will be displayed in the form. This can be useful to display alerts or information to the user when editing a record. The object can have the following properties:

NameTypeDescription
titleStringThe title of the notice. This is mandatory
idStringA unique identifier for the notice that can be used to style it with the styles property. This is mandatory
descriptionStringThe description of the notice. This is optional

Here is a quick example of usage.

Considering you have a model User with the following configuration:

.../options.ts
export const options: NextAdminOptions = {
  basePath: "/admin",
  title: "⚡️ My Admin",
  model: {
    User: {
      /**
        ...some configuration 
      **/
      edit: {
        display: [
          "id",
          "name",
          {
            title: "Email is mandatory",
            id: "email-notice",
            description: "You must add an email from now on",
          } as const,
          "email",
          "posts",
          "role",
          "birthDate",
          "avatar",
          "metadata",
        ],
        styles: {
          _form: "grid-cols-3 gap-4 md:grid-cols-4",
          id: "col-span-2 row-start-1",
          name: "col-span-2 row-start-1",
          "email-notice": "col-span-4 row-start-3",
          email: "col-span-4 md:col-span-2 row-start-4",
          posts: "col-span-4 md:col-span-2 row-start-5",
          role: "col-span-4 md:col-span-2 row-start-6",
          birthDate: "col-span-3 row-start-7",
          avatar: "col-span-4 row-start-8",
          metadata: "col-span-4 row-start-9",
        },
        /** ... some configuration */
      },
    },
  },
};

In this example, the email-notice notice will be displayed in the form before the email field. Notice example