Document Resource in Frappe-UI
Document Resource is a powerful wrapper built on top of the Resource module, specifically designed for handling single documents within applications that utilize the Frappe Framework backend. This feature streamlines interactions with individual documents, providing a structured and efficient way to manage data.
Key Features
- Automatic Fetching: Automatically retrieves the specified document based on the provided
doctype and name.
- CRUD Operations: Offers built-in methods to create, read, update, and delete document records.
- Event Handling: Allows developers to define custom behaviors on success or error events.
- Method Integration: Supports integration with whitelisted backend methods for extended functionalities.
Usage
1. Creating a Document Resource
To interact with a specific document, create a document resource by specifying the doctype and name of the record. This resource will automatically fetch the document data.
Example in Vue (Composition API)
<template>
<div v-if="todo.doc">
<div>
<h1>{{ todo.doc.description }}</h1>
<Badge>{{ todo.doc.status }}</Badge>
</div>
<Button @click="todo.setValue.submit({ status: 'Closed' })">
Mark as Closed
</Button>
<Button @click="todo.sendEmail.submit({ email: todo.doc.owner })">
Send Email
</Button>
</div>
</template>
<script setup>
import { createDocumentResource, Button, Badge } from 'frappe-ui'
const todo = createDocumentResource({
doctype: 'ToDo',
name: '1',
whitelistedMethods: {
sendEmail: 'send_email',
},
})
</script>
Explanation:
createDocumentResource: Initializes the document resource for the ToDo doctype with the record name '1'.
whitelistedMethods: Registers the sendEmail method, allowing it to be invoked as a resource.
- Template Usage: Displays the document's
description and status, and provides buttons to update the status and send an email using the registered method.
2. Using Options API
For those leveraging Vue's Options API, you need to register the resourcesPlugin and define your resources within the component.
main.js
import { createApp } from 'vue'
import App from './App.vue'
import { resourcesPlugin } from 'frappe-ui'
const app = createApp(App)
app.use(resourcesPlugin)
app.mount('#app')
Component.vue
<template>
<div v-if="$resources.todo.doc">
<div>
<h1>{{ $resources.todo.doc.description }}</h1>
<Badge>{{ $resources.todo.doc.status }}</Badge>
</div>
<Button @click="$resources.todo.setValue.submit({ status: 'Closed' })">
Mark as Closed
</Button>
<Button @click="$resources.todo.sendEmail.submit({ email: $resources.todo.doc.owner })">
Send Email
</Button>
</div>
</template>
<script>
export default {
resources: {
todo() {
return {
type: 'document',
doctype: 'ToDo',
name: '1',
whitelistedMethods: {
sendEmail: 'send_email',
},
}
},
},
}
</script>
Explanation:
resourcesPlugin: Registers the resources system within the Vue application.
resources Key: Defines the todo resource, specifying the doctype, name, and any whitelistedMethods.
- Template Usage: Accesses the
todo resource via this.$resources.todo to display and interact with the document.
Configuration Options and API
Configuration Options
When creating a document resource, you can specify various options to customize its behavior:
doctype: (String) The name of the doctype (e.g., 'ToDo').
name: (String) The unique identifier of the document record.
whitelistedMethods: (Object) Defines backend methods that can be invoked as resources.
- Event Handlers:
onError: Function to handle errors from failed requests.
onSuccess: Function to handle successful responses.
transform: Function to modify the document data before it's set.
delete: Object containing onSuccess and onError for delete operations.
setValue: Object containing onSuccess and onError for value-setting operations.
Example Configuration
let todo = createDocumentResource({
doctype: 'ToDo',
name: '1',
whitelistedMethods: {
sendEmail: 'send_email',
},
onError(error) {
console.error('Error fetching todo:', error)
},
onSuccess(data) {
console.log('Todo fetched successfully:', data)
},
transform(doc) {
doc.open = false
return doc
},
delete: {
onSuccess() {
console.log('Todo deleted successfully')
},
onError(error) {
console.error('Error deleting todo:', error)
},
},
setValue: {
onSuccess() {
console.log('Todo updated successfully')
},
onError(error) {
console.error('Error updating todo:', error)
},
},
})
API Methods and Properties
The DocumentResource instance (todo in the examples) exposes several properties and methods to interact with the document:
todo.doc: Contains the fetched document data.
todo.reload(): Reloads the document data from the backend.
todo.update({ doctype, name }): Updates the resource configuration with a new doctype and name.
Resource Operations
-
Fetching the Document
todo.get: The resource responsible for fetching the document.
todo.get.loading: Boolean indicating if the fetch is in progress.
todo.get.error: Contains error information if the fetch fails.
todo.get.promise: The promise associated with the fetch request.
-
Updating Document Values
todo.setValue: Resource for setting multiple field values.
todo.setValue.submit({ field: value, ... }): Submits the new values to be updated on the document.
todo.setValueDebounced: Similar to setValue but debounced (e.g., submits after 500ms).
- Usage: Useful for scenarios like live search or auto-saving where immediate submission isn't ideal.
-
Deleting the Document
todo.delete: Resource for deleting the document.
todo.delete.submit(): Initiates the delete operation.
-
Custom Whitelisted Methods
todo.sendEmail: Represents the send_email method defined in whitelistedMethods.
todo.sendEmail.submit({ email: 'example@example.com' }): Calls the send_email method with the specified parameters.
Practical Example
Here's a comprehensive example demonstrating how to utilize the DocumentResource in a Vue component to manage a ToDo document:
<template>
<div v-if="todo.doc">
<div>
<h1>{{ todo.doc.description }}</h1>
<Badge :status="todo.doc.status" />
</div>
<Button @click="closeTodo">Mark as Closed</Button>
<Button @click="sendTodoEmail">Send Email</Button>
<Button @click="deleteTodo">Delete Todo</Button>
</div>
<div v-else>
Loading...
</div>
</template>
<script setup>
import { createDocumentResource, Button, Badge } from 'frappe-ui'
// Initialize the document resource
const todo = createDocumentResource({
doctype: 'ToDo',
name: '1',
whitelistedMethods: {
sendEmail: 'send_email',
},
onError(error) {
alert(`Error: ${error.message}`)
},
onSuccess(data) {
console.log('Todo loaded:', data)
},
transform(doc) {
// Example transformation
doc.fullDescription = `${doc.description} - (Status: ${doc.status})`
return doc
},
})
// Method to mark the todo as closed
const closeTodo = () => {
todo.setValue.submit({ status: 'Closed' })
}
// Method to send an email related to the todo
const sendTodoEmail = () => {
todo.sendEmail.submit({ email: todo.doc.owner })
}
// Method to delete the todo
const deleteTodo = () => {
if (confirm('Are you sure you want to delete this todo?')) {
todo.delete.submit()
}
}
</script>
Explanation:
- Template: Displays the todo's description and status, along with buttons to close, send an email, or delete the todo.
- Script Setup:
createDocumentResource: Initializes the resource with event handlers and a transformation function.
closeTodo: Updates the status field to 'Closed'.
sendTodoEmail: Invokes the send_email method with the owner's email.
deleteTodo: Confirms and deletes the todo document.
Best Practices
- Error Handling: Always define
onError handlers to manage and respond to potential errors gracefully.
- Optimistic Updates: Consider using
setValueDebounced for scenarios requiring delayed updates to enhance user experience.
- Method Whitelisting: Only expose necessary backend methods via
whitelistedMethods to maintain security and control.
- Data Transformation: Utilize the
transform function to preprocess or augment document data before it's used in the frontend.
Conclusion
The DocumentResource in Frappe-UI offers a structured and efficient way to manage individual documents within your Vue applications. By leveraging its built-in methods, event handling, and integration capabilities, developers can streamline data interactions and enhance the overall functionality of their applications.
For further customization and advanced usage, refer to the Frappe-UI Documentation or consult the Frappe Framework community.