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
naveen reddy 68naveen reddy 68 

issue on trigger without showing any error

I need to query new records after inserting a record but my below trigger doesnt show any error but even doesnt display any records either please suggest me


trigger con1 on Contact (before insert,before update) 
{
    Map<id,Name> MP = new Map<id,Name>();
    for(Contact con:Trigger.new)
    {
        if(con.LastName != null)
        {
            con.Title = 'kelly1';
            
        }
        if(con.Title == 'kelly1')
            {
            list<contact> c1=[select id,lastName From Contact where id=:trigger.NewMap.keyset()];
            system.debug(c1);
            }
    }
    
    
}
Best Answer chosen by naveen reddy 68
EldonEldon
Hi naveen

If you need to use record ids u need to use after trigger,

Try this code,
 
trigger con1 on Contact (after insert,after update) 
{
    list<id> RecordId=new list<id>();
    
    for(Contact con:Trigger.new)
    {
        if(con.LastName != null)
        {
            RecordId.add(con.id);
        }
    }
    
    list<contact> c1=[select id,lastName From Contact where id in :RecordId];
    system.debug(c1);
    
}


Let me know if it solved
 

All Answers

Nayana KNayana K
In before insert, before update contexts record is not yet commited to database. So, list<contact> c1=[select id,lastName From Contact where id=:trigger.NewMap.keyset()]; line doesn't make any sense. On before insert, trigger.NewMap.keyset() will be empty. On before update, Trigger.New wll give you the record info which you are updating so need need to explicitly query.

Can you please elaborate your requirement in detail?

 
RudrarajuRudraraju
Hi Naveen,

First of all, we shouldn't do DML operations(Update, Delete, Insert, Queryies) in for loop. Let me know your requirement, so that I can help you.
EldonEldon
Hi naveen

If you need to use record ids u need to use after trigger,

Try this code,
 
trigger con1 on Contact (after insert,after update) 
{
    list<id> RecordId=new list<id>();
    
    for(Contact con:Trigger.new)
    {
        if(con.LastName != null)
        {
            RecordId.add(con.id);
        }
    }
    
    list<contact> c1=[select id,lastName From Contact where id in :RecordId];
    system.debug(c1);
    
}


Let me know if it solved
 
This was selected as the best answer
Harish RamachandruniHarish Ramachandruni
Hi ,

What error u looking for and what is your senioroi .


Explain me  i hope i can help you  .



Regards,
Harish.R.