Frappe Syntax Controllers logo

Frappe Syntax Controllers

Organization
Impertio-Studio
frappe-syntax-controllers

Use when writing Python Document Controllers for ERPNext/Frappe DocTypes. Covers lifecycle hooks (validate, on_update, on_submit), controller override, submittable documents, autoname patterns, UUID naming (v16), and the flags system. Keywords: document controller, lifecycle hook, validate, on_update, on_submit, autoname, naming series, flags, v14-v16, controller example, lifecycle hook order, when to use validate, Python DocType class.

Overview

PublisherImpertio-Studio
RepositoryFrappe_Claude_Skill_Package
Skill namefrappe-syntax-controllers
Stars
180
Forks
53
Bundled files
10
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 10 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by Impertio-Studio on GitHub. Read the source before you install it.

Installation

Install the Frappe Syntax Controllers AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Impertio-Studio/Frappe_Claude_Skill_Package.git /tmp/Frappe_Claude_Skill_Package
mkdir -p .claude/skills
cp -r /tmp/Frappe_Claude_Skill_Package/skills/source/syntax/frappe-syntax-controllers .claude/skills/frappe-syntax-controllers
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Frappe Syntax Controllers in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Frappe Syntax Controllers on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Frappe Syntax Controllers is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Frappe Syntax: Document Controllers

Document Controllers are Python classes that define all server-side logic for a DocType. EVERY DocType has exactly one controller file. The controller class extends frappe.model.document.Document.

Quick Reference

python
import frappe
from frappe import _
from frappe.model.document import Document

class SalesOrder(Document):
    def autoname(self):
        """Custom naming logic. Sets self.name."""
        self.name = f"SO-{self.customer_code}-{frappe.utils.now_datetime().year}"

    def validate(self):
        """MAIN validation — runs on EVERY save (insert and update).
        Changes to self ARE saved to database."""
        if not self.items:
            frappe.throw(_("Items are required"))
        self.total = sum(item.amount for item in self.items)

    def on_update(self):
        """After save — changes to self are NOT saved.
        Use frappe.db.set_value() for post-save field changes."""
        self.notify_linked_docs()

    def on_submit(self):
        """After submit (docstatus 0 -> 1). Create ledger entries here."""
        self.create_gl_entries()

    def on_cancel(self):
        """After cancel (docstatus 1 -> 2). Reverse ledger entries here."""
        self.reverse_gl_entries()

    @frappe.whitelist()
    def recalculate(self):
        """Exposed to client JS via frm.call('recalculate')."""
        self.total = sum(item.amount for item in self.items)
        return {"total": self.total}

File Location and Naming

DocType NameClass NameFile Path
Sales OrderSalesOrderselling/doctype/sales_order/sales_order.py
My Custom DocMyCustomDocmodule/doctype/my_custom_doc/my_custom_doc.py

Rule: DocType name -> PascalCase class -> snake_case filename. ALWAYS match exactly.


Lifecycle Hook Execution Order

INSERT (new document)

before_insert -> before_naming -> autoname -> before_validate -> validate
-> before_save -> [db_insert] -> after_insert -> on_update -> on_change

SAVE (existing document)

before_validate -> validate -> before_save -> [db_update]
-> on_update -> on_change

SUBMIT (docstatus 0 -> 1)

before_validate -> validate -> before_submit -> [db_update]
-> on_submit -> on_update -> on_change

CANCEL (docstatus 1 -> 2)

before_cancel -> [db_update] -> on_cancel -> on_change

UPDATE AFTER SUBMIT

before_update_after_submit -> [db_update]
-> on_update_after_submit -> on_change

DELETE

on_trash -> [db_delete] -> after_delete

DISCARD [v15+]

before_discard -> [db_set docstatus=2] -> on_discard

Complete hook reference with parameters: See lifecycle-methods.md


Hook Selection Decision Tree

What do you need to do?
|
+-- Validate data or calculate fields?
|   +-- validate (changes to self ARE saved)
|
+-- Action AFTER save (emails, sync, linked docs)?
|   +-- on_update (changes to self are NOT saved)
|
+-- Only for NEW documents?
|   +-- after_insert (runs once on first save only)
|
+-- Custom document name?
|   +-- autoname (set self.name)
|
+-- Before/after SUBMIT?
|   +-- Validate before submit? -> before_submit
|   +-- Create entries after submit? -> on_submit
|
+-- Before/after CANCEL?
|   +-- Check linked docs? -> before_cancel
|   +-- Reverse entries? -> on_cancel
|
+-- Cleanup before delete?
|   +-- on_trash
|
+-- React to ANY value change (including db_set)?
|   +-- on_change (MUST be idempotent)

Critical Rules

1. Changes after on_update are NOT saved

python
# WRONG - change is lost after on_update
def on_update(self):
    self.status = "Completed"  # NOT saved to database

# CORRECT - use db_set or frappe.db.set_value
def on_update(self):
    self.db_set("status", "Completed")

2. NEVER call frappe.db.commit() in controllers

python
# WRONG - breaks Frappe transaction management
def validate(self):
    frappe.db.commit()  # Can cause partial updates on error

# CORRECT - Frappe commits automatically at end of request
def validate(self):
    self.update_related()  # No commit needed

3. ALWAYS call super() when overriding

python
# WRONG - parent validation is skipped entirely
def validate(self):
    self.custom_check()

# CORRECT - parent logic preserved
def validate(self):
    super().validate()
    self.custom_check()

4. Use flags for recursion prevention

python
def on_update(self):
    if self.flags.get("from_linked_doc"):
        return
    linked = frappe.get_doc("Linked Doc", self.linked_doc)
    linked.flags.from_linked_doc = True
    linked.save()

5. NEVER put validation logic in on_update

python
# WRONG - document is already saved when this throws
def on_update(self):
    if self.total < 0:
        frappe.throw("Invalid total")  # Too late!

# CORRECT - validate BEFORE save
def validate(self):
    if self.total < 0:
        frappe.throw("Invalid total")  # Blocks save

Document Naming (autoname)

MethodExampleResultVersion
field:fieldnamefield:customer_nameABC CompanyAll
naming_series:naming_series:SO-2024-00001All
ExpressionPRE-.#####PRE-00001All
Old-style formatINV-{YYYY}-{####}INV-2024-0001Deprecated v16
hash / randomhasha1b2c3d4e5All
PromptPromptUser enters nameAll
autoincrementautoincrement1, 2, 3All
UUIDUUID550e8400-e29b-...v16+
Custom methodautoname() in controllerAny patternAll

Custom autoname Method

python
from frappe.model.naming import getseries

class Project(Document):
    def autoname(self):
        prefix = f"P-{self.customer[:3].upper()}-"
        self.name = getseries(prefix, 3)
        # Result: P-ACM-001, P-ACM-002, etc.

UUID Naming [v16+]

Set autoname = "UUID" in DocType definition. Frappe generates UUID v4.

When to use UUID:              When to use traditional naming:
- Cross-system sync            - User-facing references (SO-00001)
- Bulk record creation         - Sequential numbering required
- Global uniqueness needed     - Auditing requires readable names

Controller Extension Mechanisms

1. override_doctype_class (full replacement) [All versions]

python
# hooks.py
override_doctype_class = {
    "Sales Order": "custom_app.overrides.CustomSalesOrder"
}

# custom_app/overrides.py
from erpnext.selling.doctype.sales_order.sales_order import SalesOrder

class CustomSalesOrder(SalesOrder):
    def validate(self):
        super().validate()  # ALWAYS call super()
        self.custom_validation()

WARNING: Only ONE app can override a DocType class. Multiple overrides conflict.

2. extend_doctype_class (mixin, non-destructive) [v16+]

python
# hooks.py
extend_doctype_class = {
    "Address": ["custom_app.extensions.address.GeocodingMixin"],
    "Contact": [
        "custom_app.extensions.common.ValidationMixin",
        "custom_app.extensions.contact.PhoneMixin"
    ]
}

# custom_app/extensions/address.py
from frappe.model.document import Document

class GeocodingMixin(Document):
    @property
    def full_address(self):
        return f"{self.address_line1}, {self.city}, {self.country}"

    def validate(self):
        super().validate()
        self.geocode_address()

ALWAYS prefer extend_doctype_class over override_doctype_class in v16+. Multiple apps can safely extend the same DocType.

3. doc_events (hook individual events) [All versions]

python
# hooks.py
doc_events = {
    "Sales Order": {
        "validate": "custom_app.events.validate_sales_order",
        "on_submit": "custom_app.events.on_submit_sales_order"
    },
    "*": {  # ALL DocTypes
        "after_insert": "custom_app.events.log_creation"
    }
}

# custom_app/events.py
def validate_sales_order(doc, method=None):
    if doc.total > 100000:
        doc.requires_approval = 1

When to Use Which

Need full class replacement?     -> override_doctype_class [all versions]
Need to add methods/properties?  -> extend_doctype_class [v16+]
Need to hook one or two events?  -> doc_events [all versions]
Need to extend in v14/v15?       -> override_doctype_class or doc_events

Whitelisted Methods

Expose controller methods to client-side JavaScript with @frappe.whitelist():

python
class SalesOrder(Document):
    @frappe.whitelist()
    def send_email(self, recipient):
        """Callable from JS: frm.call('send_email', {recipient: '...'})"""
        frappe.sendmail(recipients=[recipient], message="Order confirmed")
        return {"status": "sent"}
javascript
// Client-side call
frm.call('send_email', { recipient: 'customer@example.com' })
    .then(r => frappe.msgprint(r.message.status));

Rules:

  • ALWAYS add @frappe.whitelist() decorator — without it, the method is NOT callable from client
  • The method MUST be defined on the controller class (not standalone)
  • Permission checks happen automatically (user must have read access to the document)

Submittable Documents

Documents with is_submittable = 1 follow the docstatus lifecycle:

docstatusStateEditableTransitions
0DraftYes-> 1 (Submit)
1SubmittedOnly "Allow on Submit" fields-> 2 (Cancel)
2CancelledNoNone (amend creates new Draft)

ALWAYS implement both on_submit and on_cancel as a pair. ALWAYS reverse in on_cancel what on_submit created.


Inheritance Patterns

python
# Standard controller
from frappe.model.document import Document
class MyDoc(Document): pass

# Tree DocType (hierarchical)
from frappe.utils.nestedset import NestedSet
class Department(NestedSet):
    nsm_parent_field = "parent_department"

# Virtual DocType (no database table)
class ExternalData(Document):
    def load_from_db(self): ...
    def db_insert(self, *args, **kwargs): ...
    def db_update(self, *args, **kwargs): ...
    @staticmethod
    def get_list(args): ...
    @staticmethod
    def get_count(args): ...

Type Annotations [v15+]

python
class Person(Document):
    if TYPE_CHECKING:
        from frappe.types import DF
        first_name: DF.Data
        last_name: DF.Data
        birth_date: DF.Date
        company: DF.Link

Enable auto-generation in hooks.py: export_python_type_annotations = True


Version Differences

Featurev14v15v16
Type annotationsNoAuto-generatedYes
before_discard / on_discardNoYesYes
flags.notify_updateNoYesYes
extend_doctype_classNoNoYes
UUID autonameNoNoYes
Old-style format namingYesYesDeprecated

Reference Files

FileContents
lifecycle-methods.mdAll hooks with execution order diagrams
document-api-complete.mdComplete Document API: all methods by category (CRUD, fields, DB, permissions, flags, child tables, naming)
methods.mdDocument class method signatures
events.mdAll document events in order
examples.mdComplete working controller examples
anti-patterns.mdCommon mistakes and corrections
flags.mdFlags system (doc.flags, frappe.flags)
hooks.mdController interaction with hooks.py
patterns.mdCommon controller patterns
syntax.mdController class syntax reference

Related Skills

  • frappe-syntax-serverscripts -- Server Scripts (sandbox alternative)
  • frappe-syntax-hooks -- hooks.py configuration
  • frappe-impl-controllers -- Implementation workflows
  • frappe-core-permissions -- Permission system

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Frappe Syntax Controllers AI skill do?

Use when writing Python Document Controllers for ERPNext/Frappe DocTypes. Covers lifecycle hooks (validate, on_update, on_submit), controller override, submittable documents, autoname patterns, UUID naming (v16), and the flags system. Keywords: document controller, lifecycle hook, validate, on_update, on_submit, autoname, naming series, flags, v14-v16, controller example, lifecycle hook order, when to use validate, Python DocType class.

Why use Frappe Syntax Controllers on TypingMind?

Because you install it once and use it with any model. Frappe Syntax Controllers is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Frappe Syntax Controllers in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/Impertio-Studio/Frappe_Claude_Skill_Package/tree/main/skills/source/syntax/frappe-syntax-controllers. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Frappe Syntax Controllers?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Frappe Syntax Controllers?

As many as you like. As long as a model supports skills, you can use Frappe Syntax Controllers with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Frappe Syntax Controllers AI skill free?

Yes. It is published on GitHub by Impertio-Studio under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇