function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Masahiro KawataMasahiro Kawata 

New Validation Rule gives trigger error

Hi, I'm pretty new to Salesforce (had this job about 3 weeks) and I'm trying to set up a validation rule that prevents one particular user from creating an event anywhere but in opportunities.
Here's the logic on the validation rule:

CreatedBy.Id = "00530000002EKrz" 
&& 
NOT(LEFT(WhatId,3) = "006")

Now, when I try to create an event while logged in as this user, I get the following error message:

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger Event_AfterInsert caused an unexpected exception, contact your administrator:
Event_AfterInsert: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 00UV0000001jJghMAE; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This event must be associated with an opportunity.: []: Trigger.Event_AfterInsert: line 12, column 1

So it's having some kind of problem with 'Event_AfterInsert'. That's this:
 
trigger Event_AfterInsert on Event (after insert)
{
	For (Event e : trigger.new)
    {
        For (Account a : [Select Id, Region__c from Account where Id = :e.AccountId])
	    {
	        // Update the event record
			Event[] ev = [select id, Region__c from Event where id = :e.Id];
			ev[0].Region__c = a.Region__c;
			update ev[0];
	    }
    }
}

But I have no idea where to go from here.  The 'This event must be associated with an opportunity' part of the error message is exactly what I put as my validation rule's error message, which is also confusing me.

Any help would be greatly appreciated.
Thank you!
Best Answer chosen by Masahiro Kawata
VinojVinoj
Hi Masahiro,

It looks like there may be an issue with your validation rule.  Since you're trying to prevent them from creating a record there won't be a CreatedBy.Id, instead you need to reference the current user:

$User.Id = "00530000002EKrz"
&&
NOT(LEFT(WhatId,3) = "006")

All Answers

VinojVinoj
Hi Masahiro,

It looks like there may be an issue with your validation rule.  Since you're trying to prevent them from creating a record there won't be a CreatedBy.Id, instead you need to reference the current user:

$User.Id = "00530000002EKrz"
&&
NOT(LEFT(WhatId,3) = "006")
This was selected as the best answer
Eric ShickEric Shick
Might want to look into bulkifying your trigger
Masahiro KawataMasahiro Kawata
Thank you both very much for replying.
Vinoj, your answer worked - it was so obvious!
It's a little embarassing that my problem was that I was too literal-minded for a computer.
Thanks again!