You need to sign in to do that
Don't have an account?
Re: Updating a field while inserting a record
Hi,
I am not able to update a field when a new record is saved.
Below is the code for an Custom Object Policy where I am trying to update a field "Product Id" when a new Policy Record is created.
Please find out error and provide a solution for it.
trigger PolicyProduct on Policy__c (before insert) {
List<Policy__c> poli=new List<Policy__C>();
for(List<Policy__c> policies:[select Id,Name,Product_Id__c,Status__c from Policy__c where Status__c='Active']){
for(Policy__c pol:policies){
String Id=pol.Id;
if(pol.Status__c=='Active'){
pol.Product_Id__c='PD1';
pol= new Policy__c(Id=pol.Id,Product_Id__c= pol.Product_Id__c);
poli.add(pol);
}
}
}
if(poli.size()>0)
{
try{
Database.SaveResult[] saveresults=Database.insert(poli,false);
Integer x=0;
for(Database.SaveResult svr:saveresults){
if(!svr.isSuccess())
{
Database.Error err=svr.getErrors()[0];
System.debug('Unable to insert policy'+poli[0].Name+'.Error'+err.getMessage());
}
x++;
}
}catch(Exception e){
System.debug(e);
}
}
}
Thanks,
Manga
in before insert trigger its not required to write the insert statement again.... just assign the values thats it... in the back end when the trigger is called still the records are not yet commited so u simply need to assign..
some thing like this
trigger PolicyProduct on Policy__c (before insert) {
List<Policy__c> poli=new List<Policy__C>();
for(List<Policy__c> policies:[select Id,Name,Product_Id__c,Status__c from Policy__c where Status__c='Active']){
for(Policy__c pol:policies){
String Id=pol.Id;
if(pol.Status__c=='Active')
pol.Product_Id__c='PD1';
}
}
}