You need to sign in to do that
Don't have an account?
SFDC@Error
Update Parent owner based on child
HI All
I have two custom object Object1 and Object2 and both have relationship.When I am creating Object2 record with lookup field value of object1 ,need to update record owner of object2 with object1 after record save.i have created a trigger but facing problem like
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger SyncField caused an unexpected exception, contact your administrator: SyncField: data changed by trigger for field Owner ID: id value of incorrect type: a0b0k000000sivZAAQ
I have two custom object Object1 and Object2 and both have relationship.When I am creating Object2 record with lookup field value of object1 ,need to update record owner of object2 with object1 after record save.i have created a trigger but facing problem like
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger SyncField caused an unexpected exception, contact your administrator: SyncField: data changed by trigger for field Owner ID: id value of incorrect type: a0b0k000000sivZAAQ
trigger SyncField on Object2__c (before insert, before update) { for(Object2__c ao:Trigger.new) if(Trigger.isInsert) ao.OwnerId = ao.object1__c; else if(ao.OwnerId != Trigger.oldMap.get(ao.id).OwnerId) ao.object1__c= ao.OwnerId; else if(ao.object1__c!= Trigger.oldMap.get(ao.id).object1__c) ao.OwnerId = ao.object1__c; }
I think you are requirement is a bit not clear because if you want to the change the owner of the parent based on child's owner (WRONG).
Explanation : The owner field of the parent gets updated for every child creation, Which directly states that the owner field value depends on the newest child owner's value.
Is your requirement is this for sure. Then try the following code.
Trigger SyncField on Object2__c (after insert, after update) {
List<Object1__c> oaList = new List<Object1__c>();
if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)) {
for(Object2__c o : Trigger.new) {
Object1__c oa = new Object1__c(Id = o.ParentFieldApiName);
oa.OnwerId = o.OwnerId;
oaList.add(oa);
}
update oaList;
}
}
Then the code would be :
Trigger SyncField on Object2__c (before insert, before update) {
Set<Id> parentId = new Set<Id>();
List<Object1__c> oList = new List<Object1__c>();
if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
for(Object2__c o : Trigger.new) {
parentId.add(o.ParentFieldApiName);
}
Object1__c parentVal = [select ownerId from Object1__c where id = : parentId];
for(Object2__c o : Trigger.new) {
o.ownerId = parentVal.ownerId;
oList.add(o);
}
update oList;
}
}
Please use owner.Id, instead of ownerId. It will work.