I have a Task in Salesforce with a custom record type of My Custom Record Type
. This record type has a picklist field named My Custom Field
and for this record type, I set the default value to My Default Value
.
When a new Task
is created, I want to set the record type in a before insert trigger. That is working:
trigger TaskTrigger on Task (before insert) {
for (Task newTask : Trigger.new) {
Id recordTypeId = Schema.SObjectType
.Task.getRecordTypeInfosByName()
.get('My Custom Record Type')
.getRecordTypeId()
newTask.RecordTypeId = callTaskRecordType;
}
}
However, after the insert, the default value of My Custom Field
is not set. It is null
Task myTask = new Task();
insert myTask;
// Trigger logging executes, record type is set correctly...
Task insertedTask = [SELECT RecordTypeId, My_Custom_Field__c FROM Task WHERE Id = :myTask.id];
System.debug(insertedTask.RecordTypeId); // Set properly
System.debug(insertedTask.My_Custom_Field__c); // null!
Note that if I create a Task and set the record type before insert, the default value does get set correctly
Task myTask = new Task();
myTask.RecordTypeId = callTaskRecordType;
Id recordTypeId = Schema.SObjectType
.Task.getRecordTypeInfosByName()
.get('My Custom Record Type')
.getRecordTypeId()
newTask.
insert myTask;
Task insertedTask = [SELECT RecordTypeId, My_Custom_Field__c FROM Task WHERE Id = :myTask.id];
System.debug(insertedTask.My_Custom_Field__c); // Set properly!
Why isn't the picklist getting the default value? And if this doesn't work, how could I set default values after changing the record type in a before insert?