[SalesForce] How to lock down an opportunity and prevent edits after generating a sales order

I'm new to Salesforce and even newer to apex, so I'm struggling a bit here.

My goal is to lock down an Opportunity once a sales order has been generated on my company's side. My current idea is to have a custom read-only "Locked" field within the Opportunity object. I want to use the SOAP API to update this value and then have an Apex Trigger (after update) set all the fields in the Opportunity to read-only.

Where I am getting slowed down is in writing an Apex trigger to set fields to read-only, currently I only have the boilerplate code

trigger lockOpportunity on Opportunity (after update) {
    for (Opportunity myOpp : Trigger.new){

I can get as far as setting specific values, along the lines of myOpp.Description = "opp description"; but I don't know how to access field properties to set them to read-only. Or, if there's a way to lock down the entire object in a single call, that would be even better.


Best Answer

You can't set fields to Read-Only for a specific record. There are two possible solutions and neither of them require code.

  1. Add a validation rule to the Opportunity object that has criteria something like

    Locked__c && !ISCHANGED(Locked__c) && ISCHANGED(LastModifiedDate)

  2. Create a page layout that has all the fields marked as read-only and then have a record type called Locked that has the read-only layout assigned to it. When the Locked field is checked, then have a workflow rule update the record type.

In most cases you should really use both. The validation rule is great for ensuring that it's locked in the myriad alternative ways to edit records, i.e. list view mass edit and data loader. The page layout will improve the end user experience by not letting them do a huge number of edits only to block them on save (in other words, wasting their time).

Also, in most cases you'll need to adjust the criteria for the workflow rule to allow edits by certain profiles, i.e. finance teams and system administrators.

Related Topic