ERPNext Client Script Tutorial: Dynamic Field Background Coloring

ERPNext Client Script Tutorial: Dynamic Field Background Coloring

Executive Summary & Objective

Building upon basic form validation techniques, this tutorial demonstrates how to dynamically alter the CSS background color of a form field in ERPNext based on real-time user input values.

By attaching a JavaScript Client Script to specific form events, developers can visually highlight fields depending on calculated thresholds — such as marking high values in gold and lower values in a light color.


Key Tutorial Concepts & Mechanics

1. Form Structure & Target Fields

The tutorial sets up a custom DocType containing three numeric input fields:

  • col_1: First numerical input.
  • col_2: Second numerical input.
  • col_3: Target field displaying the calculated sum of col_1 and col_2.

2. Event Trigger Optimization

  • Event Hook: The Client Script function is explicitly hooked to the col_2 field change event.
  • Execution Logic: The calculation and color update function executes only when a user modifies col_2. Changing col_1 alone will not trigger the script, ensuring targeted event execution.

3. Conditional Background Styling Logic

When col_2 is modified, the script evaluates the value of col_3:

  • Condition A (col_3 > 100): Applies a gold CSS background color to the HTML input element of col_3.
  • Condition B (col_3 <= 100): Sets the background color to a light color.

Visual Workflow & Architecture Diagram


Complete ERPNext Client Script Example

Below is the Client Script implementation illustrating the logic described in the video:

frappe.ui.form.on('My DocType', {
    // Trigger script execution specifically when col_2 changes
    col_2: function(frm) {
        // Calculate the sum of col_1 and col_2
        let total = (frm.doc.col_1 || 0) + (frm.doc.col_2 || 0);
        
        // Update col_3 with the calculated value
        frm.set_value('col_3', total);
        
        // Target the field input element to apply dynamic CSS styling
        if (frm.doc.col_3 > 100) {
            frm.get_field('col_3').$input.css('background-color', 'gold');
        } else {
            frm.get_field('col_3').$input.css('background-color', 'lightpink');
        }
    }
});

Key Takeaways for Developers

  • DOM Manipulation in Frappe: Accessing frm.get_field('field_name').$input allows direct manipulation of input CSS properties like background color within Frappe forms.
  • Event-Driven Development: Binding Client Scripts to specific field events (col_2) prevents unnecessary script execution overhead on every form change.
  • Incremental Practice: Practicing basic JavaScript manipulations in ERPNext Client Scripts builds a foundation for developing complex custom workflows and UI enhancements.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *