Here’s an Apex Trigger that ensures when a Position (custom object) is created, and it is marked as a "New Position," the Open Date, Min Pay, and Max Pay fields are populated with default values if they are not already provided.
trigger SetDefaultValuesOnPosition on Position__c (before insert) {
for (Position__c position : Trigger.new) {
// Check if it is a New Position
if (position.Type__c == 'New Position') {
// Set Open Date if not already populated
if (position.Open_Date__c == null) {
position.Open_Date__c = Date.today();
}
// Set Min Pay if not already populated
if (position.Min_Pay__c == null) {
position.Min_Pay__c = 10000;
}
// Set Max Pay if not already populated
if (position.Max_Pay__c == null) {
position.Max_Pay__c = 15000;
}
}
}
}
Explanation of the Code
Trigger Event:
- Runs on the
before insert
event to populate fields before the record is saved to the database.
- Runs on the
Logic:
- Checks if the
Type__c
field (assumed to identify the Position type) is set to"New Position"
. - Ensures that Open Date, Min Pay, and Max Pay fields are only populated with default values if they are null.
- Checks if the
Bulk Processing:
- Loops through all records in
Trigger.new
to handle bulk inserts.