0

I have a Web-to-Case form on our community portal for users to submit new cases. I have a trigger that checks to see if the new case has an attachment on it in order to be submitted, basically making the attachment required in order for it to be created for certain types of cases. However. The trigger fires off even when there is an attachment on the new case form. I realize that the case has not yet been created and therefore the trigger applies. Here is a draft of my code:

trigger CreateCaseTrigger on Case (before insert) {


    for(Case c:Trigger.New) {


            Attachment a = new Attachment();
            try {
               a = [Select Id, Name from Attachment where ParentId =:c.Id];
            }
            catch(Exception e) {
               a = null;
            }

            if (a == null)
               c.addError('Add an attachment before you close the Case');

    } 

Any help would be greatly appreciated!

1

1 Answer 1

2

Parent records are saved before children records; in a before insert trigger, the case itself doesn't even have an Id you could query with (in your code, c.Id is null). Coincidentally, this means that you can't verify that there is an attachment until it's too late. There's no way you use the standard UI and require a case using a trigger. You'd have to write a Visualforce page or Lightning component, and force your users to use that instead. This would give you the ability to check if an attachment was selected. Also, web-to-case itself is asynchronous, meaning that the user wouldn't even know their case was not submitted.

You must log in to answer this question.

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