You need to sign in to do that
Don't have an account?

i am getting dml exception plz help me with this code.i created two custom objects position1__c and candidate1__c with lookup relation.when ever i update position email than corresponding candidate email should gets updated.
this is my code
trigger trigb23 on position1__c (after update) {
list<candidate1__c> clist=new list<candidate1__c>();
for(position1__c p:trigger.new){
list<candidate1__c> cnd=[select id,name,position1__c from candidate1__c where position1__c=:p.id];
candidate1__c c=new candidate1__c();
c.position1__c=p.Id;
c.email__c=p.email__c;
clist.add(c);
}
update clist;
}
trigger trigb23 on position1__c (after update) {
list<candidate1__c> clist=new list<candidate1__c>();
for(position1__c p:trigger.new){
list<candidate1__c> cnd=[select id,name,position1__c from candidate1__c where position1__c=:p.id];
candidate1__c c=new candidate1__c();
c.position1__c=p.Id;
c.email__c=p.email__c;
clist.add(c);
}
update clist;
}
Please try below code. Thanks
Hemant
All Answers
Well, I guess the first mistake is that you don't want to create new records (am i right?). DML exception probabily is ocorring because you are not setting ID field (required for update) for new candidate__c.
Take a look in the code below. I guess it will fulfill to your business needs:
List<position1__c> positions = Trigger.new;
Map<Id,position1__c> oldMap = Trigger.oldMap;
List<position1__c> updatedPositions = new List<position1__c>();
for( position1__c p :positions ) {
// Email field has changed.
if( p.email__c != oldMap.get( p.Id ).email__c ) {
updatedPositions.add( p.Id );
}
}
list<candidate1__c> clist=new list<candidate1__c>();
Map<String,List<candidate1__c>> positionsWithCandidatesMap = new Map<String,List<candidate1__c>>();
List<candidate1__c> cnds = [select id,name,position1__c from candidate1__c where position1__c in :updatedPositions];
for( candidate1__c cnd : cnds ) {
if( !positionsWithCandidatesMap.contaisKey( cnd.position1__c ) ) {
positionsWithCandidatesMap.put( cnd.position1__c, new List<candidate1__c>() );
}
positionsWithCandidatesMap.get( cnd.position1__c ).add( cnd );
}
for( position1__c p: updatedPositions ){
List<candidate1__c> cndsToUpdate = positionsWithCandidatesMap.get( p.Id );
for( candidate1__c cndToUpdate : cndsToUpdate ) {
cndToUpdate.email__c = p.email__c;
}
clist.addAll( cndsToUpdate );
}
update clist;
}
Let me know if it helps somehow.
Regards.
Please try below code. Thanks
Hemant
If you don't need to compare old values to new ones, just remove the condition. The new code is:
Regards.