2
0
mirror of https://github.com/frappe/books.git synced 2024-12-25 20:11:15 +00:00
books/docs/models/controllers.md

64 lines
1.7 KiB
Markdown
Raw Normal View History

2018-01-10 12:49:52 +00:00
# Controllers
2018-01-10 12:54:27 +00:00
In Frappe.js you can extend the metadata class as well as the document class for a particular DocType.
2018-01-10 12:49:52 +00:00
You can write event handlers in controllers, by declaring a `.js` file in the `models/doctype/` folder along with the model file.
2018-02-22 07:36:28 +00:00
You must also mind the controller to the model file by the `documentClass` property.
2018-01-10 12:54:27 +00:00
## Naming
2018-01-10 12:49:52 +00:00
1. The name of the controller class must be the slugged name of the DocType (example `todo`)
2. The name of the `meta` class must be the name of the controller class prefixed by `meta_` (example `meta_todo`)
To add a standard handler, you must bind all handlers in `setup` method.
2018-01-10 12:54:27 +00:00
## Document Controller
You can bind events to the controller that will be called when an action is completed on a document or its property.
The document controller represents a single record and is subclassed from the `frappe.document.Document` class
2018-01-10 12:49:52 +00:00
```js
2018-01-16 06:09:17 +00:00
const frappe = require('frappejs');
2018-01-10 12:49:52 +00:00
2018-01-10 12:54:27 +00:00
// extend the document and add event handlers
class todo extends frappe.document.Document {
validate() {
if (!this.status) {
this.status = 'Open';
}
}
}
```
## Metadata Controller
The `meta` class contains actions that are done on a group of objects and a document represents a single object. So properties and actions related to the group will be part of the `meta` class.
```js
2018-01-10 12:49:52 +00:00
// extend the meta class
class todo_meta extends frappe.meta.Meta {
2018-02-08 12:28:51 +00:00
getRowHTML(data) {
2018-01-10 12:49:52 +00:00
return `<a href="#edit/todo/${data.name}">${data.subject}</a>`;
}
}
```
2018-01-10 12:54:27 +00:00
2018-01-10 12:49:52 +00:00
### Controller Events
Standard events on which you can bind handlers are
2018-06-25 07:49:11 +00:00
- `beforeInsert`
- `beforeUpdate`
2018-01-10 12:49:52 +00:00
- `validate` (called before any write)
2018-06-25 07:49:11 +00:00
- `afterInsert`,
- `afterUpdate` (called after any write)
- `beforeSubmit`
- `afterSubmit`
- `beforeCancel`
- `afterCancel`
- `beforeDelete`
- `afterDelete`