fflib-apex-common-samplecode
fflib-apex-common-samplecode copied to clipboard
Example of before insert trigger
Because records in a before insert/before update trigger should not be updated, it would be good to have an example of how to deal with them. The sample code only contains examples of on after trigger events that pair nicely with UoW and other domains.
Do you mean how to override the onBeforeInsert and onBeforeUpdate base class methods?
That's the one. I've found that doing onBefore methods requires some extra consideration over the onAfter methods. Mainly because changes made to the records in an onBefore trigger are automatically committed at the end of the transaction, and registering the record as dirty in a unit of work throws a dml exception (to be expected).
I've been writing procedural code in the onBefore method to avoid using the domain methods that would otherwise take a unit of work, and I have a gut feel that it's not the best use of the patterns.
I'm interested in how you'd deal with onBefore methods to gauge whether I'm on the right path or not.
Ok i think i've getting the gist (no pun intended) of the kind of sample you want to see. Can you provide a small sudo example perhaps to help me nail what your currently doing in my mind?
@afawcett could you explain how would you use a Service method in a Before Insert/Update trigger handler event?
Im confused how to deal with that because I need to update a field on every record of a Before Update. I won't be creating anything.
It is simply like this:
Trigger
public override void onBeforeUpdate(Map<Id, SObject> existingRecords) {
computeBody();
}
private void computeBody() {
DSP_DocumentSigningRequestService.computeBody(this.Records);
}
Service
public void computeBody( List<DocumentSigningRequest__c> records) {
DSP_IDocumentSigningRequests documentSigningRequests = (DSP_IDocumentSigningRequests) Application.Domain.newInstance(records);
for (
DocumentSigningRequest__c documentSigningRequest : documentSigningRequests.getDocumentSigningRequests()
) {
documentSigningRequest.setBody('Bla');
}
}
}
Domain
public List<DocumentSigningRequest__c> getDocumentSigningRequests(){
return (List<DocumentSigningRequest__c>) getRecords();
}
public void setBody(String body){
for (DocumentSigningRequest__c documentSigningRequests : getDocumentSigningRequests()){
documentSigningRequests.Body__c = body;
}
}
Would this be the way to do it?