Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The NetSuite Pro

The NetSuite Pro Logo The NetSuite Pro Logo

The NetSuite Pro Navigation

  • Home
  • About Us
  • Tutorials
    • NetSuite Scripting
    • NetSuite Customization
    • NetSuite Integration
    • NetSuite Advanced PDF Templates
    • NetSuite Reporting & Analytics Guide
    • Real-World NetSuite Examples
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask A Question
  • Home
  • About Us
  • Tutorials
    • NetSuite Scripting
    • NetSuite Customization
    • NetSuite Integration
    • NetSuite Advanced PDF Templates
    • NetSuite Reporting & Analytics Guide
    • Real-World NetSuite Examples
  • Blog
  • Contact Us
Home/ Real-World NetSuite Examples/Auto-Populate Department & Class by Cost Center

Auto-Populate Department & Class by Cost Center

πŸ’Ό Business Requirement

The client needs a script that automatically fills in Department and Class fields on each line item based on the Cost Center selected either at the header level or at the line level.

This ensures that accounting data stays consistent across transactions and removes the need for users to manually select departments and classes for every line item.


🎯 Key Requirements

  • When a user selects a Cost Center on the Header, all line items should automatically get the corresponding Department and Class.
  • If the Cost Center on a line is modified manually, that line’s Department and Class should be updated accordingly.
  • If the Cost Center on the Header changes during Edit, all line-level Department and Class values should update to match the new Cost Center.
  • Script should work for Sales Orders, Purchase Orders, and Journal Entries.
  • On Edit mode, if a user manually changes a line-level cost center, the header cost center should not override it.

🧩 Case Scenarios

#ScenarioExpected Behavior
1Cost Center selected on HeaderDepartment and Class auto-populate on all lines
2Cost Center changed on Header after lines existAll line Departments and Classes update automatically
3Cost Center manually changed on one LineOnly that line updates (header values remain)
4Record opened for EditHeader values no longer override existing lines

🧠 Solution Approach

To handle both real-time and backend updates, we’ll use a combination of:

  1. Client Script β†’ Runs in real time in the browser as users interact.
    • Triggers on fieldChanged event when costcenter is updated on either header or line.
    • Updates department and class fields instantly.
  2. User Event Script β†’ Runs during record creation or edit in the backend (server-side).
    • Ensures that Department and Class are correct even for records created by CSV import, scripts, or integrations.
    • Re-applies mapping logic in beforeSubmit or afterSubmit.

🧩 Data Source: Cost Center Mapping

Create a Custom Record (Cost Center Mapping) to store relationships between Cost Center β†’ Department β†’ Class.
Example fields:

FieldIDDescription
Cost Centercustrecord_cost_centerReference to Cost Center record
Departmentcustrecord_cost_center_deptDepartment linked to that Cost Center
Classcustrecord_cost_center_classClass linked to that Cost Center

The scripts will lookup this mapping record to find the appropriate department and class values.


🧩 SuiteScript 2.1 β€” Client Script (for Real-Time UI Updates)

/**
 * @NApiVersion 2.1
 * @NScriptType ClientScript
 * @Author The NetSuite Pro
 * @Description Auto-populates Department and Class based on Cost Center selection
 */

define(['N/search', 'N/currentRecord'], (search, currentRecord) => {

  function fieldChanged(context) {
    const rec = context.currentRecord;
    const fieldId = context.fieldId;

    // Header-level change
    if (fieldId === 'custbody_cost_center') {
      const costCenter = rec.getValue('custbody_cost_center');
      if (!costCenter) return;

      // Loop through each line and update
      const lineCount = rec.getLineCount({ sublistId: 'item' });
      for (let i = 0; i < lineCount; i++) {
        const mapping = getCostCenterMapping(costCenter);
        if (mapping) {
          rec.selectLine({ sublistId: 'item', line: i });
          rec.setCurrentSublistValue({ sublistId: 'item', fieldId: 'department', value: mapping.department });
          rec.setCurrentSublistValue({ sublistId: 'item', fieldId: 'class', value: mapping.class });
          rec.commitLine({ sublistId: 'item' });
        }
      }
    }

    // Line-level change
    if (fieldId === 'custcol_cost_center') {
      const line = context.line;
      const costCenter = rec.getCurrentSublistValue({ sublistId: 'item', fieldId: 'custcol_cost_center' });
      if (!costCenter) return;
      const mapping = getCostCenterMapping(costCenter);
      if (mapping) {
        rec.setCurrentSublistValue({ sublistId: 'item', fieldId: 'department', value: mapping.department });
        rec.setCurrentSublistValue({ sublistId: 'item', fieldId: 'class', value: mapping.class });
      }
    }
  }

  function getCostCenterMapping(costCenterId) {
    const results = search.create({
      type: 'customrecord_cost_center_mapping',
      filters: [['custrecord_cost_center', 'is', costCenterId]],
      columns: ['custrecord_cost_center_dept', 'custrecord_cost_center_class']
    }).run().getRange({ start: 0, end: 1 });

    if (results && results.length > 0) {
      return {
        department: results[0].getValue('custrecord_cost_center_dept'),
        class: results[0].getValue('custrecord_cost_center_class')
      };
    }
    return null;
  }

  return { fieldChanged };
});

🧩 SuiteScript 2.1 β€” User Event Script (for Server-Side Accuracy)

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 * @Description Ensures Department and Class are updated per Cost Center in backend processes
 */

define(['N/record', 'N/search', 'N/log'], (record, search, log) => {

  function beforeSubmit(context) {
    const rec = context.newRecord;
    const headerCostCenter = rec.getValue('custbody_cost_center');

    const lineCount = rec.getLineCount({ sublistId: 'item' });

    for (let i = 0; i < lineCount; i++) {
      let lineCostCenter = rec.getSublistValue({ sublistId: 'item', fieldId: 'custcol_cost_center', line: i });
      const effectiveCostCenter = lineCostCenter || headerCostCenter;

      if (!effectiveCostCenter) continue;

      const mapping = getMapping(effectiveCostCenter);
      if (!mapping) continue;

      rec.setSublistValue({ sublistId: 'item', fieldId: 'department', line: i, value: mapping.department });
      rec.setSublistValue({ sublistId: 'item', fieldId: 'class', line: i, value: mapping.class });
    }
  }

  function getMapping(costCenterId) {
    const results = search.create({
      type: 'customrecord_cost_center_mapping',
      filters: [['custrecord_cost_center', 'is', costCenterId]],
      columns: ['custrecord_cost_center_dept', 'custrecord_cost_center_class']
    }).run().getRange({ start: 0, end: 1 });

    if (results && results.length) {
      return {
        department: results[0].getValue('custrecord_cost_center_dept'),
        class: results[0].getValue('custrecord_cost_center_class')
      };
    }
    return null;
  }

  return { beforeSubmit };
});

βœ… Deployment Plan

Record TypeScript TypeTriggerPurpose
Sales OrderClient + User EventfieldChanged / beforeSubmitReal-time + backend
Purchase OrderClient + User EventfieldChanged / beforeSubmitReal-time + backend
Journal EntryUser Event onlybeforeSubmitBackend-only automation

πŸ“Š Benefits

BenefitDescription
AccuracyConsistent Department and Class per Cost Center
SpeedInstant update for users and integrations
FlexibilityWorks across SO, PO, and JE
MaintenanceMapping easily managed through a custom record
Share
  • Facebook

Leave a ReplyCancel reply

Sidebar

Ask A Question

Stats

  • Questions 6
  • Answers 6
  • Best Answers 0
  • Users 3
  • Popular
  • Answers
  • Rocky

    Issue in running a client script in NetSuite SuiteScript 2.0 ...

    • 1 Answer
  • admin

    How can I send an email with an attachment in ...

    • 1 Answer
  • admin

    How do I avoid SSS_USAGE_LIMIT_EXCEEDED in a Map/Reduce script?

    • 1 Answer
  • admin
    admin added an answer The issue is usually caused by following Wrong script file… September 14, 2025 at 10:33 pm
  • admin
    admin added an answer Steps to send an Invoice PDF by email: define(['N/email', 'N/render',… August 28, 2025 at 3:05 am
  • admin
    admin added an answer This error means your script hit NetSuite’s governance usage limit… August 28, 2025 at 3:02 am

Top Members

Rocky

Rocky

  • 1 Question
  • 22 Points
Begginer
Sophie1022

Sophie1022

  • 0 Questions
  • 20 Points
Begginer
admin

admin

  • 5 Questions
  • 2 Points

Trending Tags

clientscript netsuite scripting suitescript

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Menu

  • Home
  • About Us
  • Tutorials
    • NetSuite Scripting
    • NetSuite Customization
    • NetSuite Integration
    • NetSuite Advanced PDF Templates
    • NetSuite Reporting & Analytics Guide
    • Real-World NetSuite Examples
  • Blog
  • Contact Us

Quick Links

  • NetSuite Scripting
  • NetSuite Customization
  • NetSuite Advanced PDF Template
  • NetSuite Integration
  • NetSuite Reporting & Analytics

Subscribe for NetSuite Insights....

© 2025 The NetSuite Pro. All Rights Reserved