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
cherialcherial 

How to insert a new record...

Hello Members-

Can i able to insert a new record into a custom object using triggers and classes?(There are two custom objects Admission__c, Student__c. Defined a trigger on Admission__c. when this trigger is fired on Admission__c object i want to insert a new record into Student__c). Is it possible or not?

If possible, please guide me the way to write the code.

Thanks,
-Nath
hisrinuhisrinu
Yes, you can do this.


Code:
trigger admin on Admission__c (before insert, before update) 
{
    for(Admission__c a:Trigger.new)
    {
        Student__c s = new Student__c(Name = 'TEST');
        insert s;
    }
}

This is the just a sample, you can modify this and you can insert the record into the student object.
Hope this helps you.
 

cherialcherial
Thanks Srini for ur quick reply.

I tried the above code. When i inserted a new record or updated a record in Admission__c object then no new record is inserted into the Student__c object. When i clicked student__c object tab i can't see a new record with 'TEST' Name


Apart from this i tried with another(My approach) code.Below are the trigger and class codes:

trigger admin_trig1 on Admission__c (before insert, before update)
 {
    Admission__c[] a1=trigger.new;
    admin_prac1.m1(a1);
 
}

public class admin_prac1 {
    public static void m1(Admission__c[] a1)
    {
        Student__c std=new Student__c(Name='TEST');
        //Student__c.createable=true;
        try
        {
              insert std;
          }
          catch(DMLException e)
          {
               system.assert(false,'Error creating Calc:'+e.getDMLMessage(0));
          }
       
    }

}


No errors but When i inserted a new record or updated a record in Admission__c object then no new record is inserted into the Student__c object. When i clicked student__c object tab i can't see a new record with 'TEST' Name

-Nath
hisrinuhisrinu
Hi Nath,

Just check the debug log whether it is calling the class or not.
Try to place some debug statements and then observe them through the logs.