Auto-Generate Student Roll Number using Apex
Project Overview:
This project automates the generation of unique roll numbers for students in Salesforce. When a new student is admitted, their roll number is automatically generated based on their Class and Admission Year. This eliminates manual errors and ensures unique identification.
Objectives:
– Automate roll number assignment.
– Ensure uniqueness across students.
– Generate roll numbers in a standard format.
– Reduce manual data entry effort.
System Design:
Student__c (Custom Object)
• Name → Student Name (Standard)
• Class__c → Class (Picklist: BCA, BBA, MCA)
• Admission_Date__c → Admission Date (Date)
• Roll_Number__c → Roll Number (Text, Auto-generated, Read-Only)
Roll Number Format
Format: Class-Year-Sequence
Example:
– First Student in BCA 2025 → BCA-2025-1
– Second Student in BCA 2025 → BCA-2025-2
– First Student in BBA 2025 → BBA-2025-1
Implementation:
Apex Trigger
trigger AutoGenerateRollNumber on Student__c (before insert) {
Map<String, Integer> maxNumbersMap = new Map<String, Integer>();
for (Student__c stu : Trigger.new) {
if (stu.Class__c != null && stu.Admission_Date__c != null) {
String year = String.valueOf(stu.Admission_Date__c.year());
String key = stu.Class__c + ‘-‘ + year;
maxNumbersMap.put(key, 0);
}
}
List<Student__c> existingStudents = [
SELECT Roll_Number__c FROM Student__c
WHERE Roll_Number__c != NULL
];
for (Student__c s : existingStudents) {
String[] parts = s.Roll_Number__c.split(‘-‘);
if (parts.size() == 3) {
String key = parts[0] + ‘-‘ + parts[1];
Integer seq = Integer.valueOf(parts[2]);
if (maxNumbersMap.containsKey(key) && seq > maxNumbersMap.get(key)) {
maxNumbersMap.put(key, seq);
}
}
}
for (Student__c stu : Trigger.new) {
if (stu.Class__c != null && stu.Admission_Date__c != null) {
String year = String.valueOf(stu.Admission_Date__c.year());
String key = stu.Class__c + ‘-‘ + year;
Integer nextNum = maxNumbersMap.get(key) + 1;
stu.Roll_Number__c = key + ‘-‘ + nextNum;
maxNumbersMap.put(key, nextNum);
}
}
}
Example Execution:
Student Name | Class | Admission Date | Roll Number (Auto) |
---|---|---|---|
Shoeb | BCA | 2025-08-28 | BCA-2025-1 |
Amir | BCA | 2025-09-02 | BCA-2025-2 |
Sana | BBA | 2025-08-30 | BBA-2025-1 |
Benefits:
– Automated roll number generation.
– No duplicates within same Class-Year.
– Scalable for multiple classes and years.
– Error-free roll number assignment.
Limitations:
– Bulk insert of more than 200 students may hit SOQL governor limits.
– Possible concurrency issues if many users add students at the same time.