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
Suresh RaghuramSuresh Raghuram 

Creating the same record always

I wrote a trigger to invoke this class, but ths  is populating the same record when ever i am creating the new contact

public class createphantom
{
//contact cnt = new contact();
List<contact> cnt=[select Name,id,ReportsToId, AccountId from Contact limit 10];
phantom__c pnt = new phantom__c();
public void phantom()  //Method to be invoked by the trigger
{
    pnt.Name = 'patient123';
    pnt.External_Key__c = cnt[0].Id;
    pnt.Last_Name__c = cnt[0].Name;
    pnt.Reports_To__c = cnt[0].ReportsToId;
    pnt.Account_Name__c = cnt[0].AccountId;

Insert pnt;

}
}

Andy BoettcherAndy Boettcher

You need to iterate through your list - you're just calling the first index in your list.

 

public class createphantom {

	List<contact> cnt=[select Name,id,ReportsToId, AccountId from Contact limit 10];

	// Create an empty list to keep DML out of the loop!
	List<phantom__c> lstPhantomNew = new List<phantom__c>();

	public void phantom() {

	    for(Contact thisP : cnt) {

	  
		    phantom__c pnt = new phantom__c();
		    pnt.Name = 'patient123';
		    pnt.External_Key__c = thisP.Id;
		    pnt.Last_Name__c = thisP.Name;
		    pnt.Reports_To__c = thisP.ReportsToId;
		    pnt.Account_Name__c = thisP.AccountId;

		    lstPhantomNew.add(pnt);
	    }

	}

	if(lstPhantomNew.size() > 0) { insert lstPhantomNew; }
}

 -Andy

 

Suresh RaghuramSuresh Raghuram

It is again reading the same old record

RizwiRizwi

If you want to query for just inserted contact, this is not the way to do it. Is that what you want. then user Trigger.new

Andy BoettcherAndy Boettcher

Tell us exactly what you are trying to do.

Suresh RaghuramSuresh Raghuram

trigger on contact obj will invoke this createPhantom class, when a new contact is created and populates the phantom object with few fields of the contact