1

Here's my trigger:

 trigger updateFieldUponEmail on EmailMessage (before insert) {
        //find parentId of EmailMessage
        //where case.Id = parentId, increment number field isUpdated
        SObjectField EmailMessageID = EmailMessage.parentID;
        for(Case c: [SELECT timesUpdated__c FROM Case WHERE Id = :EmailMessageID]){
            c.timesUpdated__c++;
        }
    }

I want it to increment a number field of a case that the EmailMessage is a child of. I'm fairly new to Java/APEX so I'm not sure how exactly to do this, but I got this far. However, I keep getting the error: Invalid bind expression type of Schema.SObjectField. What can I do? Thank you!

1 Answer 1

3

You cannot bind (:variable name) an sObjectField in an soql query. It has to be an actual variable so simply change the variable type to the ID type which will hold the value instead of sObjectField which is the entire field object:

trigger updateFieldUponEmail on EmailMessage (before insert) {
        Set<ID> caseIDs = new Set<ID>();

        for(EmailMessage msg : trigger.new){
            if(msg.parentID.getsObjectType() == Case.sObjectType)
               caseIDs.add(msp.parentID);
        }

        Case[] casesToUpdate = [SELECT timesUpdated__c FROM Case WHERE ID IN :CaseIDs];
        for(Case c: casesToUpdate){
            c.timesUpdated__c = c.timesUpdated__c == null ? 1 : c.timesUpdated__c +1;
        }

     update casesToUpdate;

    }

I have updated the code to bulkify it

9
  • I had my code like that before, but that gives me: Illegal assignment from Schema.SObjectField to Id at line 4, which was why I made it of type sObjectField.
    – AKor
    Oct 16, 2015 at 14:51
  • Well, you have to define EmailMessage. U thought it was a placeholder. Updated. You will have to bulkily the trigger. Right now it assumes only ONE record will ever enter the trigger. If doing ilk updates this WILL NOT work right and you will have to cycle through the records
    – Eric
    Oct 16, 2015 at 14:52
  • @AKor - I have updated it to be bulkified. I also change your incremental code as if the field was null it would throw an error
    – Eric
    Oct 16, 2015 at 14:58
  • Hmm, when I updated the code it threw this error: Method does not exist or incorrect signature: Case.sObjectType(). So I commented out that line and I get: Incorrect SObject type: EmailMessage should be Case at line 1 column 1. Does SF think that the logic is for a case only?
    – AKor
    Oct 16, 2015 at 15:13
  • @AKor - Basic debugging...... No method it is a property so I removed the () see updated code. Sorry about that
    – Eric
    Oct 16, 2015 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.