You need to sign in to do that
Don't have an account?
santhosh kumar 15
i want to change the balance field in customer obj based on the transaction obj type field (customer and transaction obj are lookup relation.) tell me the problem with code??
trigger trans on transaction__c (after insert) {
list<customer__c> lt =new list<customer__c>();
for(transaction__c tr:trigger.new){
customer__c cu = [select id,name from customer__c where id=:tr.customer__cid];
if(tr.type=='deposite')
cu.balance__c=cu.balance__c+tr.amount__c;
else if(tr.type=='withdraw'){
cu.balance__c=cu.balance__c-tr.amount__c;
}
}
}
list<customer__c> lt =new list<customer__c>();
for(transaction__c tr:trigger.new){
customer__c cu = [select id,name from customer__c where id=:tr.customer__cid];
if(tr.type=='deposite')
cu.balance__c=cu.balance__c+tr.amount__c;
else if(tr.type=='withdraw'){
cu.balance__c=cu.balance__c-tr.amount__c;
}
}
}
Try following code;
If its helps, please mark as best answer so it will help to other who will serve same problem.
Thanks!
First of all your code is not bulkified. Remember not to insert a query inside of a loop.
Also, the DML related to customer is not there.
I would go for something like below lines.
trigger trans on transaction__c (after insert)
{
if(trigger.isAfter)
{
Set<Id> cusIds = new Set<Id>();
list<customer__c> customerToUpdate =new list<customer__c>();
for(transaction__c tr:trigger.new)
{
cusIds.add(tr.customer__r.id);
}
Map<Id, customer__c> cuMap = new Map<Id, customer__c> {[select id,name from customer__c where id IN :cusIds]};
customer__c cuToupdate = new customer__c();
for(transaction__c tr:trigger.new)
{
cuToUpdate = cuMap.get(tr.customer__r.id);
if(tr.type=='deposite')
cuToUpdate.balance__c=cuToUpdate.balance__c+tr.amount__c;
else if(tr.type=='withdraw'){
cuToUpdate.balance__c=cuToUpdate.balance__c-tr.amount__c;
customerToUpdate.add(cuToUpdate);
}
update customerToUpdate;
}
}
I hope it helps.
If its helps, please mark as best answer so it will help to other who will serve same problem.
Thanks!
thanks to all.
here it showing error as invalid field type for sobject transaction_c....( deposite,withdraw are picklist types.)
if(tr.type=='deposite')
how can we rectify this??
Or maybe it is "type__c"