0

Hello fellow code lovers, I am attempting to learn apex code and stuck on a problem. Since most of you guys here are avid code lovers and excited about problem solving, I figured I could ran by problem by.

I am attempting to Create a Trigger on an object called Book that does the following: On Delete, all associated Chapters are also deleted There is also an object named Chapter that is has a lookup to book.

Here is my attempt. This is my first ever attempt at apex so please be patient. Is anyone willing to dabble in this piece of code?

 trigger DeleteChaptersTrigger on Book__c (before delete) {
 List<Book__c> book = Trigger.old;
 List<Chapter__c> chapters = new List<Chapter__c>();
 Set set = new Set();

  for (Book__c b :books){
  if ()
   }
 }
2
  • Do you have full control over the account and its design/setup? Commented Feb 12, 2013 at 23:21
  • @GerardSexton Yes I do. Commented Feb 12, 2013 at 23:23

2 Answers 2

3

You need to write all trigger with consideration that the trigger might be processing many records at any one time so you need to bulkify your trigger code.

Here are the variables that available on the trigger object.

You want to get all the record ids that will be deleted. Use the keyset method on the oldmap to get this info without looping and creating your own collection. Then you can just delete the records returned from the query.

trigger DeleteChaptersTrigger on Book__c (before delete) {
    Set<string> bookids = Trigger.oldMap.keyset();
    delete [SELECT Id FROM Chapter__c WHERE Book__c IN :bookids];     
}

Apex code is unlike other languages where it gets confused with reuse of used words, like set as a variable name. Apex is also case insensitive.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 but you don't need keyset while binding like that, you can bind collection and it will be cast down to collection of Ids automatically :)
@eyescream Oh, its an automatic cast? So delete [SELECT Id FROM Chapter__c WHERE Book__c IN :Trigger.old]; is also valid?
2

Since you have full control, I recommend changing the way your custom objects are related to each other.

A chapter has no meaning/value without a book so we want to change the relationship between the two.

Remove the lookup on the Chapter object and replace it with a master-detail. When a master record gets deleted, Salesforce automatically deletes the detail related records. This is what you want, and without coding.

2 Comments

@Gerald Sexton I am actually following an exercise. and that it asked for a lookup.
well then, that information affects the type of answer that can be given.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.