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
john miirjohn miir 

Please help with trigger

Hi I am new to salesforce trying to write a trigger. I need to update a field in custom object when ever a field Y changes from blank to some value  in contract object the value should be saved to the custom object field X.

Thanks in adavance

I wrote the following
trigger Caseidcustom on Case (after update, after insert) {
    list<Custom object>  i =  new list<Custom object> ();
    
    for(Case cs :trigger.new)
    {
        Case oldCase = trigger.oldMap.get(cs.X);
        
        if(trigger.isInsert) {
            Custom object o = new Custom object ();
            o.Y = cs.X;
            
        }
        
        if(trigger.isUpdate && oldCase != null ) {
            Custom object o = new Custom object ();
            o.Y = cs.X;  
        }
        
    }
}

getting Review all error messages below to correct your data.
Apex trigger Caseidcustom caused an unexpected exception, contact your administrator: Caseidcustom: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: ()
Best Answer chosen by john miir
Vladimir SaturaVladimir Satura
trigger.oldMap is available only for Update triggers, not for insert. When you are inserting new record, there is no previous (old) value. 

User trigger.oldMap only after your check if it is update operation (if(trigger.isUpdate)). 
Additionally trigger.oldMap is map of IDs so your X in trigger.oldMap.get(cs.X) must be Id => trigger.oldMap.get(cs.Id);
+ you are saying you need to udpate a field on some records but you are creating a new records (new Custom object ())
+ those custom objects are never saved anywhere