+ Start a Discussion
Sfdc wonderSfdc wonder 

Delete old values after insert new data

hi,
i hav a custom object,i want to insert only single value.when i insert new data in to object,its delete old data.

i hav tried the following trigger

trigger DeleteRecord on SampleTest__c (after insert)
{
SampleTest__c[] accs=new List<SampleTest__c>();

for(SampleTest__c acc:trigger.old)
{
accs.add(acc);
 
}
delete accs;

}
khillan bhardwajkhillan bhardwaj
Hi ,
your above trigger would show null point exception as trigger.old return null on insert even. as per my understanding you need to delete all created record from database when you try to create new record of SampleTest . so need to write code like as follow:

trigger DeleteRecord on SampleTest__c (after insert)
{
SampleTest__c[] accs=[select id from SampleTest__c where In Not IN : trigger.newMap.keySet()];
if(accs.size() > 0)
          delete accs;

}
Damien Phillippi033905702927186443Damien Phillippi033905702927186443
Or simpler

<pre>
trigger DeleteRecord on SampleTest__c (after insert)
{
  delete [SELECT Id FROM SampleTest__c WHERE Id NOT IN :Trigger.new];
}
</pre>
Damien Phillippi033905702927186443Damien Phillippi033905702927186443
Why wouldn't you simply edit the existing data instead of inserting new data anyways?  (Remove insert permissions for all profiles)