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

Deleting/Reassigning an object from an Apex Trigger
Hi, I have two classes with a master-detail relationship. It's currently set up so that object2 points to object1 and can access properties like this:
obj2.obj1__r.property
Object 2 also has a status field. When I set that field to say 'Done', I would like to change the master-detail relationship so that it points to a completely new object. The purpose of this: I would basically like to archive object2 so it doesn't show up in a list when I look at the object1 Tab.
I'm not sure how to go about this. I think I can just query for the ID of the appropriate object1 and do the following:
LIST<object1> object1IDs = [SELECT id FROM object1 WHERE name = 'Done'];
for (object 2 myvar: trigger.old)
myvar.obj1__c = ID;
But I know this is wrong, any hints?
Thanks!
~Weyland
You're going to run into issues changing the Master in a Master-Detail relationship.
e.g. example code
objectmaster__c x = new objectmaster__c();
insert x;
objectmaster__c x2 = new objectmaster__c();
insert x2;
objectdetail__c y = new objectdetail__c(objectmaster__c = x.Id);
insert y;
y.objectmaster__c = x2.id;
update y;
This will lead to System.SObjectException: Field is not writeable: ObjectDetail__c.ObjectMaster__c
You can accomplish this by cloning with a new Master, then deleting the original.
However, I think the best approach to this problem would be to adjust what you're looking at. You can filter list views and related lists to exclude 'Done' status, which sounds like it would solve your problem.
All Answers
You're going to run into issues changing the Master in a Master-Detail relationship.
e.g. example code
objectmaster__c x = new objectmaster__c();
insert x;
objectmaster__c x2 = new objectmaster__c();
insert x2;
objectdetail__c y = new objectdetail__c(objectmaster__c = x.Id);
insert y;
y.objectmaster__c = x2.id;
update y;
This will lead to System.SObjectException: Field is not writeable: ObjectDetail__c.ObjectMaster__c
You can accomplish this by cloning with a new Master, then deleting the original.
However, I think the best approach to this problem would be to adjust what you're looking at. You can filter list views and related lists to exclude 'Done' status, which sounds like it would solve your problem.
I am not getting your req clearly
LIST<object1> object1IDs = [SELECT id FROM object1 WHERE name = 'Done'];
for (object 2 myvar: trigger.old)
myvar.obj1__c = ID;
By this I under stand both object1 and object2 has Status field
1) So when status in Object2 record changes to Done you want to change the master also with status "Done" , but how would you deterimne that which record should be new master when more then one record of Object1 has status done. Is there any business rule for this
2) What we can do inmaster detail is we have to dlete current detail and insert new one with new master , as master reference can not be updated.
Please provide answers to above questions.