0

I need to create a trigger that will prevent the deletion of a task by anyone other than the creator. I don't know about writing code so I'm hoping someone can help me out with this. It would be an assigned task on a custom object called Closings if that makes any difference. Help!?

trigger NoDeleteonAssignedTask on Task (before delete) {
String ProfileId = UserInfo.getProfileId();String UserID = Userinfo.getUserId(); 
List<Profile> profiles=[select id from Profile where name='PB Administrator'];

if (1!=profiles.size())
{
   // unable to get the profiles - handle error
}
else
{

for (Task a : Trigger.old)      

IF(a.IsAssigned__c==True &&(UserID!=a.CreatedbyID && (profileId!=profiles[0].id )))
{
     Apexpages.addMessage(new Apexpages.message(ApexPages.Severity.ERROR,'deletetaskerror'));

            }
        }
}
5
  • 2
    I didn't downvote, but typically questions asking for a solution without demonstrating an attempt are not particularly well received. Please visit the help center and read How to Ask. Welcome to SFSE!
    – Adrian Larson
    Commented Jun 28, 2016 at 15:29
  • 1
    Thank you for letting me know Adrian. I will revise to show attempts. I appreciate your help!
    – JenB
    Commented Jun 28, 2016 at 16:50
  • Any luck here @JenB?
    – Adrian Larson
    Commented Jul 13, 2016 at 13:20
  • @Adrian Larson I'm trying but I'm not a developer so this is requiring a great deal of reading and piecing together for me. The only thing I'm stuck on is having it display a VF page instead of Custom Label. This is my code.
    – JenB
    Commented Jul 14, 2016 at 15:31
  • You need to use the addError method, not ApexPages.addMessage...
    – Adrian Larson
    Commented Jul 14, 2016 at 15:59

1 Answer 1

5

You need to write a delete trigger.

  • Validations should happen before delete.
  • You can get the Id of the running user via UserInfo.getUserId().
  • You can compare the CreatedById to the running user Id.
  • You can validate in an Apex Trigger using the SObject.addError method.
  • I recommend implementing a handler pattern.
  • I recommend putting the error message in a Custom Label.
  • Make sure you stick to One Trigger Per Object.
3
  • 4
    Enabler...lol....
    – Eric
    Commented Jun 28, 2016 at 15:42
  • 1
    Alright @Eric, I made my advice very generic so that it's not spoon-feeding.
    – Adrian Larson
    Commented Jun 28, 2016 at 15:57
  • I will post what I come up with. This approach is VERY MUCH appreciated as I want to learn these things but am overwhelmed with understanding the different approaches to automatically handling the data. Don't let them bust your chops - you are TEACHING me!
    – JenB
    Commented Jun 28, 2016 at 16:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .