Dose adminjs support default value for property?
Hello, I'm using adminjs with mongoose. Suppose my schema have a property with default value like this:
const MySchema = new Schema({
key: { type: String, required: true },
level: { type: Number, default: 1, required: true },
});
In adminjs resource page, there is no default value for 'level', only empty input box.
So dose adminjs support default value for property? Thanks.
Mongoose should set your level to 1 if you leave the form field empty, but the form is not autofilled with your ORM's/ODM's defaults.
Thanks. So it there any method which make resource admin webpage use the default value? or just set an initial value when resource creating page shown.
I don't think there's an easy way currently. We plan to make changes to new action so that it allows you to fetch some data from the backend, but currently I think you'd have to create a custom component for specific properties.
Bump 👊 I am also interested in setting up default values for certain properties in the new action. Too bad this doesn't work yet.
Could this be done using an action?
Currently the only way is to use search params in the url:
https://demo.adminjs.co/app/resources/Category/actions/new?name=example
I did it by adding a hook method to before property like so:
import { ActionContext, ActionRequest } from "adminjs";
const setDefaultValuesFromQueryParams = (queryParams: string[]) => async (request: ActionRequest, context: ActionContext): Promise<ActionRequest> => {
const { query = {}, } = request
// check if query params are present in the request and inject them in the context in edit or request payload in new
queryParams.forEach((param) => {
if (query[param] !== undefined) {
switch (context.action.name) {
case 'edit':
if (query.product !== undefined) {
context.record.params = {
...context.record.params,
[param]: { id: query[param] },
};
}
break;
default:
if (query.designStudySection !== undefined) {
request.payload = {
...request.payload,
product: query.designStudySection,
};
}
}
}
});
return request;
}
export default setDefaultValuesFromQueryParams;
Then in resource options:
// resource options
options: {
actions: {
new: {
before: [setDefaultValuesFromQueryParams(['product'])],
after: [/* redirectToAction('Product', 'show') a hook for redirection also*/]
},
edit: {
showInDrawer: false,
before: [setDefaultValuesFromQueryParams(['product'])],
after: [/* redirectToAction('Product', 'show')*/]
},
}
}