function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Help on Trigger???



I would like to write a trigger on First__c object. Trigger objective is

- if new First__c created then udpate User role into custom field on First__c object

- Only if First__c.OwnerId field value change then update User role into custom field on First__c object


Can someone share any example?




not really sure the requirements are clear here but it sounds like you can do this with just workflow.


1. create custom object First__c

2. Create custom field on that object with whatever name you want (for example Owner_Role__c).  this is just a text type field.

3. Create workflow rule on First__c object that fires everytime a record is created or edited.  Workflow rule criteria should be done as this formula:


DATEVALUE(CreatedDate) = TODAY(), 


4.  Create a field update on the workflow rule that updates the Owner_Role__c (or whetever you call it) to this formula value:




5.  Activate workflow rule.

6. test with 2 users who both have a different role.  create a new First__c object record.  workflow will fire an update the field with your role.  Login as another user with another role, change owner on the record, and the field will update to that new role


does that work?  if not please be more specific in your requirements as they weren't totally clear to me. 


sorry for the requirements unclear...

I was trying to write a trigger if First__c.OwnerId has changed then update the Owner_Role__c value from User Object. The following trigger does the job.

trigger updateOwnerSales on First__C (before insert, before update) {
    List<Id>ownerId = new List<Id>();
    List<User>userAccount = new List<User>();
    for (First__c fc :
        //if(fc.OwnerId != Null) 
    Map<Id, User> userMap = new Map<Id, User>([Select Id, Role__c from User where Id In :ownerId]);
    for(First__c fcc :
        fcc.Owner_Role__c = userMap.get(fcc.OwnerId).Role__c;


But, How can i make sure above trigger only fire when new record created or OwnerId change? Not on, if i update the Owner_Role__c value manually.


Thanks in advanced.


you should use a declarative solution over a programmatic one every time if it works.  it's just best practice.  does the workflow not accomplish your objective?  a trigger should be considered last when all declarative solutions definitely won't work.