Library Management with Frappe Framework
Controller Methods
Faris Ansari
May 19, 2021

Controller methods allow you to write business logic during the lifecycle of a document.

Let's create our second doctype: Library Member. It will have 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)

Library Member DocType

After you have created the doctype, go to Library Member list, clear the cache from Settings > Reload and create a new Library Member.

If you notice, the Full Name field is not shown in the form. This is because we set it as Read Only. It will be shown only when it has some value.

Let's write code in our python controller class such that Full Name is computed automatically from First Name and Last Name.

Open your code editor and open the file library_member.py and make 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 ''}'

We wrote the logic in the before_save method which runs every time a document is saved. This is one of the many hooks provided by the Document class. You can learn more about all the available hooks at Controller docs.

Now, go back and create another Library Member and see the Full Name show up after save.

Questions
F-string syntax generates error
A AMF
1 year ago
Post
Dismiss
Unterminated expression in f-string; missing close brace
Unterminated expression in f-string; missing close brace
C captain
7 months ago
Post
Dismiss
missing close brace
missing close brace
James Fong
1 month ago
Post
Dismiss

self.full_name = f'{self.first_name} {self.last_name or ""}'

self.full_name = f'{self.first_name} {self.last_name or ""}'

James Fong
1 month ago
Post
Dismiss

self.full_name = f'{self.first_name} {self.last_name or ""}'

self.full_name = f'{self.first_name} {self.last_name or ""}'

Want to discuss?
Post it here, our mentors will help you out.
When to use Server Script vs editing .py files?
JH Jason Hunt
1 year ago
Post
Dismiss
I have found there are some differences in them; editing .py files seems to give control over libraries to include and has less security restrictions. Perhaps a section can be added on when and how to use this feature?
I have found there are some differences in them; editing .py files seems to give control over libraries to include and has less security restrictions. Perhaps a section can be added on when and how to use this feature?
Want to discuss?
Post it here, our mentors will help you out.
GIF Images are not loading in the course
DM Divyesh Mangroliya
2 years ago
Post
Dismiss
GIF images are not loading in the course. Please fix that. Thanks.
GIF images are not loading in the course. Please fix that. Thanks.
Want to discuss?
Post it here, our mentors will help you out.