Implementing Controller Methods in Empress

Introduction

In Empress, the Controller Methods play a pivotal role in allowing developers to instill business logic during the lifecycle of a document. They offer an array of functionalities that developers can harness to create a more intuitive and efficient application. This guide will guide you through the process of implementing a controller method in a document lifecycle, focusing on a practical example of creating a new document type called Library Member.

Creating the Library Member Doctype

To commence, we will create a new doctype, labeled Library Member. This doctype will encompass the following fields:

  1. First Name (Data, Mandatory)
  2. Last Name (Data)
  3. Full Name (Data, Read Only)
  4. Email Address (Data)
  5. Phone (Data)

Once the doctype is successfully created, navigate to the Library Member list, and clear the cache by selecting Settings > Reload. Now, create a new Library Member. You will notice that the Full Name field is not displayed in the form, owing to its Read Only status. This field will only be visible once it contains a value.

Implementing Controller Methods

The next step involves writing code in the Python controller class so that the Full Name field is automatically populated with the First Name and Last Name.

To do this, open your code editor and navigate to the file library_member.py. Implement the following changes:

library_member.py

class LibraryMember(Document):
    # This method will run every time a document is saved
    def before_save(self):
        self.full_name = f'{self.first_name} {self.last_name or ""}'

This script invokes the before_save hook, which is one of the many hooks provided by the Document class in Empress. This particular hook is executed every time a document is saved, making it perfect for our current application. As the name suggests, it runs before the save operation, ensuring that the Full Name is updated before the document is saved.

Note: If the above code snippet doesn’t execute as expected, verify that server-side scripts are enabled and then restart the bench using the following command:

bench --site <your_site> set-config server_script_enabled true

Wrapping up

With the controller method successfully implemented, you can now create another Library Member and observe the Full Name field being populated automatically upon saving.

This guide has demonstrated how the Controller Methods feature in Empress can be utilized to automate tasks and introduce business logic into the lifecycle of a document. By leveraging these functionalities and integrating them into your application, you can create more efficient and intuitive software solutions.