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 Custom Segment (Cost Center)

Auto-Populate Department & Class by Custom Segment (Cost Center)

πŸ’Ό Business Context

In this scenario, the Cost Center is not a standard field but a Custom Segment created through Customization β†’ Lists, Records & Fields β†’ Segments.

This segment is visible on:

  • The transaction Header, and
  • Each Line Item sublist.

Your requirement remains the same:
Whenever a user selects or changes a Cost Center segment, the corresponding Department and Class should automatically populate on that line (or all lines if changed at the header).


🎯 Updated Functional Rules

  1. When the Cost Center (Custom Segment) on Header changes β†’ All lines get Department and Class values based on the mapping.
  2. When a Cost Center (Custom Segment) on a line changes β†’ Only that line updates.
  3. During Edit β†’ Header changes update all lines unless line-level cost centers are explicitly changed.
  4. The script should support:
    • Sales Orders
    • Purchase Orders
    • Journal Entries
  5. The mapping of Cost Center β†’ Department β†’ Class remains in a custom mapping record.

🧠 Technical Approach

Because Cost Center is a custom segment, its field ID follows this pattern:

cseg_<segmentid>

For example, if your custom segment is named β€œCost Center”, its internal ID might be:

cseg_cost_center

You can confirm it by inspecting a record in the browser or using the Field Explorer in the script editor.

Your script will reference this segment’s field ID on both header and line levels.


🧩 Updated Script Logic

Below is the revised and human-readable SuiteScript 2.1 code to handle custom segment fields.

Client Script (Real-Time UI Updates)

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

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

  // Replace with your segment field ID
  const SEGMENT_FIELD_ID = 'cseg_cost_center';

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

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

      const mapping = getCostCenterMapping(costCenter);
      if (!mapping) return;

      const lineCount = rec.getLineCount({ sublistId: 'item' });
      for (let i = 0; i < lineCount; i++) {
        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 (segment field on item line)
    if (fieldId === SEGMENT_FIELD_ID) {
      const costCenter = rec.getCurrentSublistValue({ sublistId: 'item', fieldId: SEGMENT_FIELD_ID });
      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.length > 0) {
      return {
        department: results[0].getValue('custrecord_cost_center_dept'),
        class: results[0].getValue('custrecord_cost_center_class')
      };
    }
    return null;
  }

  return { fieldChanged };
});

User Event Script (Server-Side / Integration Safety)

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 * @Description Ensures Department and Class are populated per Custom Segment (Cost Center)
 */

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

  const SEGMENT_FIELD_ID = 'cseg_cost_center';

  function beforeSubmit(context) {
    const rec = context.newRecord;
    const headerCostCenter = rec.getValue(SEGMENT_FIELD_ID);
    const lineCount = rec.getLineCount({ sublistId: 'item' });

    for (let i = 0; i < lineCount; i++) {
      let lineCostCenter = rec.getSublistValue({
        sublistId: 'item',
        fieldId: SEGMENT_FIELD_ID,
        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.length) {
      return {
        department: results[0].getValue('custrecord_cost_center_dept'),
        class: results[0].getValue('custrecord_cost_center_class')
      };
    }
    return null;
  }

  return { beforeSubmit };
});

🧩 Technical Highlights

AreaImplementation
Segment HandlingReferences cseg_cost_center on both header and lines
Mapping SourceCustom record customrecord_cost_center_mapping
Supported TransactionsSales Order, Purchase Order, Journal Entry
Client ScriptHandles real-time updates in the UI
User Event ScriptEnsures accuracy for imports and back-end operations
DeploymentbeforeSubmit event for backend + fieldChanged event for UI

βœ… Benefits

BenefitDescription
AccuracyEnsures consistent financial classification
Real-Time UpdatesUpdates fields as soon as Cost Center changes
Integration SafeWorks for scripts, CSVs, and SuiteTalk
AuditabilityMapping stored in one central record
ConfigurableSupports different cost center logic per subsidiary

πŸ“˜ Example Summary

This automation is especially powerful for companies using Custom Segments to track financial dimensions like Cost Center, Division, or Profit Center.

It keeps your Department and Class fields aligned with the selected segment, ensuring accurate reporting and saving your accounting team hours of manual data entry every month.

Share
  • Facebook

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