0% found this document useful (0 votes)
6 views7 pages

PeopleCode Developer Cheat Sheet

Uploaded by

muhammad.ammad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

PeopleCode Developer Cheat Sheet

Uploaded by

muhammad.ammad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PeopleCode Developer Handbook

A practical, example-heavy cheat sheet for PHP/JS developers learning PeopleCode.

1) Variables, Types & Scope


Declare with scope keywords: Local, Global, Component, Instance. Primitive types include string, number, boolean,
date, datetime, time; objects include Record, Row, Rowset, SQL, File, arrays and classes.
/* Comments: use REM ... ; for single-line, or /* ... */ for block */
Rem Single line comment;
/* Multi
line comment */

Local string &name;


Local number &count;, &i;
Local boolean &ok;
Local date &today;
Local datetime &ts;
Global string &gCompany; /* visible everywhere in the session */
Component number &compCounter; /* visible within this component */

&name; = "Ammad";
&count; = 3;
&ok; = True;
&today; = %Date;
&ts; = %DateTime;

/* Operators */
∑ = 2 + 3; /* arithmetic: + - * / */
&cat; = "Peoplesoft " | "Rocks"; /* string concat uses | */
&bool; = (&count; > 2) And Not False;

2) Control Flow
Standard branching and loops. For loops support Step; While and Repeat-Until are also available.
/* If / ElseIf / Else */
If &count; = 0 Then
MessageBox(0, "", 0, 0, "Zero");
ElseIf &count; < 5 Then
MessageBox(0, "", 0, 0, "Less than five");
Else
MessageBox(0, "", 0, 0, "Five or more");
End-If;

/* Evaluate (switch) */
Evaluate &status;
When = "NEW"
/* ... */
When = "ACTIVE"
/* ... */
When-Other
/* ... */
End-Evaluate;

/* For */
For &i; = 1 To 10 Step 2
/* do something */
End-For;

/* While */
While &i; < 20
&i; = &i; + 1;
End-While;
/* Repeat-Until */
Repeat
&i; = &i; - 1;
Until &i; = 0;

3) Functions & Procedures


Declare with parameter types and optional return type. Functions must be defined before they are called in the
same program or placed in Include files or Application Packages.
Function AddNumbers(&a; As number, &b; As number) Returns number
Return &a; + &b;
End-Function;

/* Procedure (no return) */


Function LogMsg(&text; As string)
MessageBox(0, "Log", 0, 0, &text;);
End-Function;

Local number ∑ = AddNumbers(10, 20);


LogMsg("Sum is " | String(∑));

4) Error Handling (Try/Catch)


Catch Exception or specific subclasses (e.g., ApplicationException). Use Throw to raise errors.
Try
/* risky code */
Local number &x; = 10 / 0; /* will raise an exception */
Catch Exception &ex;
MessageBox(0, "Error", 0, 0, "Caught: " | &[Link];());
End-Try;

/* Throwing an exception */
class MyError extends Exception end-class;
Try
Throw create MyError("Custom failure");
Catch MyError &e;
MessageBox(0, "MyError", 0, 0, &[Link];());
End-Try;

5) Strings & Dates (Common Built-ins)


Frequently used helpers for text and dates/times.
Local string &s; = "PeopleCode";
Local number &pos; = Find("Code", &s;); /* returns 6 (1-based) */
Local string ∂ = SubString(&s;, 1, 6); /* 'People' */
Local string &up; = Upper(&s;); /* 'PEOPLECODE' */
Local string &low; = Lower(&s;); /* 'peoplecode' */
Local number &len; = Len(&s;);

Local date &d; = %Date; /* today's date */


Local number &y; = Year(&d;);
Local number &m; = Month(&d;);
Local number &day; = Day(&d;);
Local date &next; = AddToDate(&d;, 0, 1, 0); /* add 1 month */

6) Arrays
Resizable arrays with CreateArray or CreateArrayRept. Indexing is 1-based.
Local array of string &names; = CreateArray("Ali", "Sara");
&[Link];("Khan");
For &i; = 1 To &[Link];
MessageBox(0, "", 0, 0, &names;[&i;]);
End-For;

/* Pre-sized array */
Local array of number &nums; = CreateArrayRept(0, 3);
&nums;[1] = 10; &nums;[2] = 20; &nums;[3] = 30;

7) Component Buffer Navigation


Navigate Level 0/1/2 rowsets to read/write page buffer data.
/* Level 0 rowset */
Local Rowset &L0; = GetLevel0();
Local Row &root; = &L0;(1);

/* Get a child rowset (Scroll) on the page/component */


Local Rowset &jobRs; = &[Link];([Link]);

/* Iterate visible rows */


Local number &r;
For &r; = 1 To &[Link];
Local Row &row; = &[Link];(&r;);
/* Read/Write field values */
Local string &emplid; = &[Link];_DATA.[Link];
&[Link];_STATUS.Value = "A";
End-For;

8) Record & Row Objects


Work with Record/Field values and commit changes using Save processing or SQL.
/* Create a standalone record and select by key */
Local Record &rec; = CreateRecord(Record.PERSONAL_DATA);
&[Link]; = "000123";
If &[Link];() Then
MessageBox(0, "", 0, 0, "Name: " | &[Link];);
End-If;

/* Insert or Update; these honor PeopleCode events and defaults when used in Component context */
&[Link]; = "John Doe";
&[Link];(); /* or &[Link];(); or &[Link];(); */

9) SQLExec (single-row)
Quick one-row SELECT/INSERT/UPDATE/DELETE. Binds are :1, :2, ... Output vars must match selected columns.
Local string &name;
Local boolean &ok; = SQLExec("SELECT NAME FROM PS_PERSONAL_DATA WHERE EMPLID = :1", "000123", &name;);
If &ok; Then
MessageBox(0, "", 0, 0, "Found: " | &name;);
End-If;

/* Update example */
SQLExec("UPDATE PS_JOB SET EFF_STATUS = :1 WHERE EMPLID = :2 AND EFFDT = :3",
"A", "000123", %Date);

10) CreateSQL (multi-row cursor)


Use for multi-row results with Fetch in a loop. Always close when finished (auto-closes at scope end).
Local SQL &sql; = CreateSQL("
SELECT EMPLID, NAME
FROM PS_PERSONAL_DATA
WHERE NAME LIKE :1", "A%");

Local string &emplid;, &name;


While &[Link];(&emplid;, &name;)
MessageBox(0, "", 0, 0, &emplid; | " - " | &name;);
End-While;
&[Link];();

11) File I/O


Support for text files. Modes: "R" (read), "W" (write), "A" (append).
Local File &f; = GetFile("/tmp/[Link]", "W", "A", %FilePath_Absolute);
&[Link];("Hello from PeopleCode");
&[Link];();

/* Reading */
Local File &rf; = GetFile("/tmp/[Link]", "R", "A", %FilePath_Absolute);
Local string &line;
While &[Link];(&line;)
/* process &line; */
End-While;
&[Link];();

12) Common Events (Where to put code)


Events run at specific times. Place logic appropriately for correct behavior and performance.
/* FieldChange ([Link]) */
Rem Fires when the field value changes;
If %Component = Component.HR_JOB_DATA Then
/* validate or derive values */
End-If;

/* RowInit (RECORD) */
Rem Initialize defaults when a row becomes active;

/* SavePreChange (COMPONENT) */
Rem Final validation before save; set errors with Error or MessageBox;

/* SavePostChange (COMPONENT) */
Rem After successful save; perform follow-up actions;

/* RowInsert / RowDelete */
Rem Logic tied to row-level add/delete;

/* PageActivate (PAGE) */
Rem When page is displayed; avoid heavy SQL loops here;

13) System Variables (Useful Globals)


Handy context variables available anywhere.
/* Examples */
Local string &user; = %UserId; /* current user */
Local string &opr; = %OperatorId; /* operator id */
Local date &d; = %Date; /* current date */
Local datetime &dt; = %DateTime; /* current date/time */
Local string &action; = %Action; /* Add, Update/Display, etc. */
Local number &mode; = %Mode; /* component mode */
14) Application Classes (OO PeopleCode)
Organize logic in Application Packages; supports properties, methods, inheritance.
/* In App Package MY_APP: class Greeter */
class Greeter
property string Name get set;
method Greeter(&n; As string);
method Say();
end-class;

method Greeter
%[Link] = &n;
end-method;

method Say
MessageBox(0, "", 0, 0, "Hello, " | %[Link] | "!");
end-method;

/* Usage */
import MY_APP:*;
Local MY_APP:Greeter &g; = create MY_APP:Greeter("Ammad");
&[Link];();

15) Component Interface (CI) Basics


Automate component data entry. Set keys, then Get or Create, then Save.
Local ApiObject &ci; = GetCompIntfc(CompIntfc.HR_PERSONAL_DATA);
If &ci; = Null Then
Error ("CI not found");
End-If;

&[Link]; = "000123";
If &[Link];() Then
&[Link]; = "John Doe";
&[Link];();
End-If;

16) Integration Broker (IB)


Publish asynchronous messages or call synchronous services.
/* Publish example */
Local Message &msg; = CreateMessage(Operation.SEND_EMPLOYEE);
Local Rowset &rs; = &[Link];();
&rs;(1).[Link] = "000123";
%[Link](&msg;);

/* Sync request example */


Local Message &rq; = CreateMessage(Operation.GET_EMPLOYEE);
Local Message &rsMsg; = %[Link](&rq;);

17) Useful Patterns & Tips


Idioms you'll use all the time in real screens and batch code.
/* Safe read of a numeric field (handles Null) */
Local number &n; = Value(&[Link];_REC.MY_NUM.Value | "0");

/* Iterate only changed rows to reduce work */


Local Rowset &rs; = GetLevel0()(1).GetRowset(Scroll.MY_SCROLL);
Local number &r;
For &r; = 1 To &[Link];
Local Row &row; = &[Link];(&r;);
If &[Link]; Then
/* process */
End-If;
End-For;

/* Derive display text without saving to DB */


&[Link];_WRK.[Link] = "Computed: " | String(&n;);
End of Handbook — Happy PeopleCoding!

Common questions

Powered by AI

SQLExec and CreateSQL serve different purposes in PeopleCode for database operations. SQLExec is best suited for single-row operations such as quick SELECT, INSERT, UPDATE, or DELETE statements since it executes directly with assigned output variables matching selected columns. SQLExec is efficient for operations where result sets are predictable and limited to one row. Conversely, CreateSQL is intended for multi-row operations. It creates a SQL object and uses the Fetch method to iterate through result sets, making it suitable for handling and processing multiple rows of data. This requires explicit management of resources, such as closing the SQL object when done. Therefore, SQLExec is preferable for simple, static queries, while CreateSQL should be leveraged for handling extensive datasets that necessitate iteration .

PeopleCode provides several built-in functions for text and date manipulations. Text operations include finding substrings (Find), changing cases (Upper, Lower), and calculating lengths (Len), which are crucial for data validation and formatting tasks such as preparing display strings or ensuring uniform data entry. Date manipulations involve obtaining components of dates like year, month, and day, or computing dates dynamically using functions like AddToDate. Practical use cases include calculating deadlines by adding days or months to current dates and transforming user input cases to ensure consistent data entry in systems .

In PeopleCode, multi-row data retrieval is handled using the CreateSQL object, which allows for executing queries that return multiple rows. The process involves crafting a SQL statement with the desired parameters, executing the statement, and iterating over the results using the Fetch method, which retrieves each row sequentially. The retrieved data can then be processed as needed within the loop. This capability is significant for data management tasks as it enables comprehensive data processing without loading entire data sets into memory, thus optimizing performance and resource utilization. It also supports complex data manipulations, essential in applications that require detailed and iterative data handling .

PeopleCode embraces object-oriented programming (OOP) principles through the use of classes and application packages. This structure allows developers to encapsulate data and methods, promoting modularity, reuse, and organization. Classes can define properties and methods, with support for inheritance enabling code reuse and extension. This encapsulation not only aids in managing complexity by logically structuring code but also fosters maintainable codebases through inheritance and polymorphism. Application packages compound these benefits by grouping related classes, improving organizational clarity. Overall, PeopleCode's OOP capabilities enhance scalability, manageability, and the potential to develop robust, complex applications more efficiently .

System variables in PeopleCode, such as %UserId, %Date, or %Component, are essential for accessing contextual information about the runtime environment. These variables are useful in scenarios requiring user-specific, date-specific, or component-specific operations, like logging actions, displaying user-relevant information, or performing condition checks based on user roles. The key benefit of using system variables is their ability to facilitate dynamic and context-aware coding, reducing the hardcoding of environment-specific information and thus enhancing the adaptability and flexibility of the code across different environments and use cases .

PeopleCode supports several control flow structures, including If/ElseIf/Else conditional statements, Evaluate (switch) statements, and loop constructs such as For, While, and Repeat-Until. These structures enable developers to define logic paths and conditions effectively, catering to diverse application requirements such as decision-making processes, controlled iterations, and output based on criteria evaluation. This granularity in control is critical as it allows developers to implement complex business rules and automated decision systems, enhancing application functionality and user interaction in a structured and efficient manner .

Component Interfaces (CI) in PeopleCode provide a structured way to automate data interactions with a PeopleSoft component without user intervention. CIs allow setting keys to identify data objects, followed by data manipulation operations like Get, Create, and Save. They are instrumental in integrating with external systems by enabling automated data entry, update, and retrieval processes within PeopleSoft applications, ensuring consistency with user interface behavior and validation rules. This makes them powerful tools for batch processing and external system data synchronization tasks, as developers can script interactions that adhere to business logic defined within the application interface .

Component buffer navigation in PeopleCode is implemented by accessing rowsets through methods such as GetLevel0() and using them to manipulate data in the page buffer. It involves traversing through hierarchies of rowsets and rows, reading or writing field values to perform tasks like data validation or transformation directly on the data user interfaces. This functionality is essential because it underpins how data is managed and manipulated within a component, facilitating real-time data processing tailored to end-user interactions. It allows developers to ensure data integrity and consistency while providing users with instantaneous feedback and data updates .

PeopleCode uses various keywords to declare variable scope: Local, Global, Component, and Instance. Local variables are restricted to the function or the code block in which they are declared, ensuring encapsulation and reusability within that context. Global variables, declared with the Global keyword, are accessible throughout the session, thus being shared across different components and events within that session. Component variables' scope is limited to a particular component and persist as long as the component is active, enabling data sharing among events in the same component. Instance variables are associated with specific instances of classes or applications. Each scope has unique implications for data accessibility and lifespan, impacting the design decisions for modularization, performance, and memory management .

PeopleCode utilizes Try/Catch blocks for error handling, which enable programmers to write robust code by anticipating and managing errors. Within a Try block, code that may provoke exceptions is placed, and Catch blocks handle these exceptions by specifying actions to take when the errors occur. This mechanism ensures that unexpected behaviors or conditions are gracefully managed, reducing system crashes and maintaining application stability. Furthermore, by using specific subclasses to catch exceptions, developers can implement nuanced error handling strategies tailored to particular error types, thereby enhancing the program’s resilience .

You might also like