• Jamurai
  • NEWBIE
  • 60 Points
  • Member since 2013

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 8
    Replies
I have a really basic trigger on the EmailMessage object that updates the Case Status when an incoming email is inserted. The trigger works just fine in testing and in my test class the System.assert passes. However, the trigger has 0% test coverage and I am not able to deploy to production.  Are there limitations with this object that I'm not aware of? Any idea why this is happening?


trigger updateCaseStatus on EmailMessage (before insert) {

    List<String> applicableStatus = new String[]{
        	'Support Agent Working - Resp Provided',
            'Resolved - Waiting for Customer Approval',
            'Waiting for Customer'};
    
    Set<Id> caseIds = new Set<Id>();
    
    for (EmailMessage em : Trigger.new)
    {
        // if it is an inbound email
        if (em.Incoming)
        {
            // add Case Id to caseIds set
            caseIds.add(em.ParentId);
        }
    }
    
    // query for Cases to update
    List<Case> casesToUpdate = [SELECT Id, Status FROM Case 
                                WHERE Id IN :caseIds AND Status IN :applicableStatus];
    
    if (!casesToUpdate.isEmpty())
    {
        for (Case c : casesToUpdate)
        {
            c.Status = 'Customer Response Provided';
        }
        update casesToUpdate;
    }    
}

@isTest
private class updateCaseStatus_Test{

    static void testInboundEmail() {
        // create test case
        Case testCase = new Case(
                Subject = 'Test case01',
                Priority = 'P1 - Emergency');
        testCase.Status = 'Waiting for Customer';
    	insert testCase;
        // System.debug('testCase: ' + testCase);
        
        // create test email message
        EmailMessage em = new EmailMessage(
        	Incoming = TRUE,
            FromAddress = 'someone@somewhere.com', 
            ToAddress= 'someone@nutanix.com', 
            Subject = 'Test email', 
            TextBody = 'Test',
            ParentId = testCase.Id);
        
        Test.startTest();
        insert em;
        // System.debug('em: ' + em);
        
        // query and system assert
        Case c = [SELECT Id, Status FROM Case WHERE Id = :testCase.Id LIMIT 1];
        System.assert(c.Status == 'Customer Response Provided');
        Test.stopTest();
    }
}


Does anyone know how I can get the Account Name and use it for the String Customer without doing a SOQL Query?

I'm trying to populate the String 'Customer' with Account Name, which is a look up from the Escalation__c object.

This is my Apex controller extension:

public with sharing class addCasesToEscalation{
    public Escalation__c theEsc {get;set;}
    public String searchString {get;set;}
    public Case[] shoppingCart {get;set;}
    public Case[] AvailableCases {get;set;}
    
    public String toSelect {get; set;}
    public String toUnselect {get; set;}
    public Decimal Total {get;set;}

    public Boolean overLimit {get;set;}
    public Id EscId {get;set;}
    public Id AcctId {get;set;}
   
    //using this for PDF report attachment
    public String pdfName {get;set;}
    public String Customer {get;set;}
 
    private Case[] forRemoval = new Case[]{};
    private Set<Case> clean = new Set<Case>();

    public addCasesToEscalation(ApexPages.StandardController controller) {

       
        // Get information about the Escalation being worked on
            system.debug(controller.getRecord());
            Escalation__c theEsc = (Escalation__c)controller.getRecord();
            EscId = theEsc.Id;
           
           
        // If cases were previously selected need to put them in the "selected cases" section to start with
        shoppingCart = [select Id, CaseNumber, Subject, Status, Priority, IsClosed, CreatedDate, Escalation__c from Case where Escalation__c=:EscId order by CreatedDate Desc];

            }
   

    public void updateAvailableList() {
   
        // We dynamically build a query string and exclude items already in the shopping cart
        String qString = 'select Id, CaseNumber, Subject, Status, Priority, CreatedDate, Escalation__c, IsClosed From Case WHERE AccountId = :AcctId';
       
        // note that we are looking for the search string entered by the user in the name OR description
        // modify this to search other fields if desired
        if(searchString!=null){
            qString+= ' and (Subject like \'%' + searchString + '%\' or CaseNumber like \'%' + searchString + '%\')';
        }
       
        Set<Id> selectedEntries = new Set<Id>();
        for(Case c : shoppingCart){
            selectedEntries.add(c.Id);
        }
       
        if(selectedEntries.size()>0){
            String tempFilter = ' and Id not in (';
            for(Id i : selectedEntries){
                tempFilter+= '\'' + (String)i + '\',';
            }
            String extraFilter = tempFilter.substring(0,tempFilter.length()-1);
            extraFilter+= ')';
           
            qString+= extraFilter;
        }
              
        qString+= ' order by CreatedDate Desc';
        qString+= ' limit 101';
       
        system.debug('qString:' +qString);       
        AvailableCases = database.query(qString);
       
        // We only display up to 100 results... if there are more then we let the user know (see vf page)
        if(AvailableCases.size()==101){
            AvailableCases.remove(100);
            overLimit = true;
        }
        else{
            overLimit=false;
        }
     
    }
   
    public void addToShoppingCart(){
   
        // This function runs when a user hits "select" button next to a product
   
        for(Case c : AvailableCases){
            if((String)c.Id==toSelect){
                c.Escalation__c = EscId;
                shoppingCart.add(c);
                break;
            }
        }
       
        updateAvailableList(); 
    }
   

public PageReference removeFromShoppingCart(){
   
        // This function runs when a user hits "remove" on an item in the "Selected Cases" section
   
        Integer count = 0;
        for(Case ce : shoppingCart){

            if((String)ce.Id==toUnselect){
               
                if(ce.Id!=null&&ce.Escalation__c != null){
                    ce.Escalation__c = null;
                    forRemoval.add(ce);}
                shoppingCart.remove(count);
                break;            
            }
            count++;
        }
       
        updateAvailableList();
       
        return null;
    }
   
    public PageReference onSave(){
   
        // If previously selected devices are now removed, we need to delete them
        if(forRemoval.size()>0)
            //this is a somewhat hackey way to clean the list just in case there are duplicate cases in the list
            clean.addAll(forRemoval);
            forRemoval.clear();
            forRemoval.addAll(clean);
            update(forRemoval);
   
        // Update cases in shoppingCart
            if(shoppingCart.size()>0)
                update(shoppingCart);
       
        // After save return the user to the Escalation
        return new PageReference('/' + EscId);
    }
   
    public PageReference onCancel(){

        // If user hits cancel we commit no changes and return them to the Escalation  
        return new PageReference('/' + EscId);
    }
   
   //pdf attach extension
    public PageReference savePdf() {

    PageReference pdf = Page.escalationReport;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',EscId);

    // create the new attachment
    Attachment attach = new Attachment();

    // the contents of the attachment from the pdf
    Blob body;

    try {

        // returns the output of the page as a PDF
        body = pdf.getContent();

    // need to pass unit test -- current bug   
    } catch (VisualforceException e) {
        body = Blob.valueOf('Something went wrong');
    }
       
    pdfName = Customer + ' escalation report as of '+String.valueOf(System.today());
    attach.Body = body;
    // add the user entered name
    attach.Name = pdfName;
    attach.IsPrivate = false;
    // attach the pdf to the account
    attach.ParentId = EscId;
    insert attach;

    // send the user to the account to view results
    return new PageReference('/'+EscId);

  }
   
}

This trigger I'm writing works well for individual records, but I know it's not going to work for bulk uploads/updates because I put 3 SOQL Queries inside the For Loop (o.0)

 

Can someone please advise me how to do this without putting the queries inside the loop? 

 

I'm trying to convert leads into existing Accounts (if there is a corresponding Account to conver them into)

 

trigger myLeadConvertTrigger on Lead(after insert, after update) {
	//Create an empty list of Leads to convert
    Database.LeadConvert[] leadsToConvert = new Database.LeadConvert[]{};
    //Find a Lead Status for Leads converted - note that this will take 1 value and only the first one that it finds
    LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
    
    //For Lead being updated or inserted
    for(Lead l : Trigger.new) {
        
        // if statement logic: Lead is Lead Source 'Sign Up' and was Invited and isn't converted yet
        if(l.LeadSource == 'Sign Up' && l.Was_Invited__c=='TRUE' && !l.isConverted) {
			
            //Create a list of Accounts where the Lead Company spelling matches the Account Name
    		List<Account> accountList = [SELECT Id, Name FROM Account WHERE Name = :l.Company LIMIT 1];//Need to figure out if there's a way to take this SOQL out of the for loop
             
            //Query AccountID via Invited to app 
            List<Apps__c> accountIdViaApp = [SELECT Account_Temp__c FROM Apps__c WHERE CritterAppID__c =:l.Invited_to_app__c LIMIT 1];
            
            //Query Account ID via Added by
            List<Contact> accountIdViaAddedBy = [SELECT AccountId FROM Contact WHERE CritterUserID__c =:l.Added_by__c LIMIT 1];
            
            //Create a new Lead Convert Record
            Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(l.id);
            lc.setConvertedStatus(convertStatus.MasterLabel); //set it to the status we retrieved
            lc.setDoNotCreateOpportunity(True); //do not create an opp
            
            //if accountIdViaApp is not empty
            if(!accountIdViaApp.isempty()){lc.setAccountId(accountIdViaApp[0].Account_Temp__c);}
                
            //else if accountIdViaAddedBy is not empty
            else if(!accountIdViaAddedBy.isempty()){lc.setAccountId(accountIdViaAddedBy[0].AccountId);}
            
            //else if accountList is not empty, set the Account Id
            else if(!accountList.isempty()){lc.setAccountId(accountList[0].Id);}
                        
            //add lc to the leadsToConvert list
            leadsToConvert.add(lc);
        }
    }
	//if the leadsToConvert list is not empty
    if(!leadsToConvert.isEmpty()) {
        //convert those Leads
        Database.convertLead(leadsToConvert );
    }
}
 

 

 

trigger AppMembershipTrigger on App_Membership__c (after delete, after insert, after update, after undelete) {
  
  Set<Id> stContactIds = new Set<Id>(); 
  for(App_Membership__c member :Trigger.isDelete ? Trigger.Old : Trigger.New) {
    if(member.Contact__c != null) {
      stContactIds.add(member.Contact__c);
    }
    if(Trigger.isUpdate && Trigger.oldMap.get(member.id).Contact__c != null) {
      stContactIds.add(Trigger.oldMap.get(member.id).Contact__c);
    }
  }
  
  //APP OWNER UPDATE
  List<Contact> lstContactOwner = [Select Id,(Select Id from App_Memberships__r where Role__c = 'App Owner' AND App__r.Current_MAU__c > 150) 
                                   FROM Contact 
                                   WHERE Id IN :stContactIds];
  for(Contact contact : lstContactOwner) {
    contact.Number_of_Apps_Owner__c = contact.App_Memberships__r.size();
  }
  
  //APP MEMBER UPDATE
  List<Contact> lstContactMember = [Select Id,(Select Id from App_Memberships__r where Role__c <> 'App Owner' AND App__r.Current_MAU__c > 150) 
                                   FROM Contact 
                                   WHERE Id IN :stContactIds];
  for(Contact contact : lstContactMember) {
    contact.Number_of_Apps_Member__c = contact.App_Memberships__r.size();
  }
  
  //IOS APPS UPDATE
  List<Contact> lstiOSApps = [Select Id,(Select Id from App_Memberships__r where Platform__c = 'ios') 
                                   FROM Contact 
                                   WHERE Id IN :stContactIds];
  for(Contact contact : lstiOSApps) {
    contact.Num_of_iOS_Apps__c = contact.App_Memberships__r.size();
  }
  
  //DROID APPS UPDATE
  List<Contact> lstDroidApps = [Select Id,(Select Id from App_Memberships__r where Platform__c = 'android') 
                                   FROM Contact 
                                   WHERE Id IN :stContactIds];
  for(Contact contact : lstDroidApps) {
    contact.Num_of_Droid_Apps__c = contact.App_Memberships__r.size();
  }
  
  //UPDATE CONTACT OWNER
  if(!lstContactOwner.isEmpty()) {
    update lstContactOwner;
  }
  
  //UPDATE CONTACT MEMBER
  if(!lstContactMember.isEmpty()) {
    update lstContactMember;
  }
  
  //UPDATE IOS APPS
  if(!lstiOSApps.isEmpty()) {
    update lstiOSApps;
  }
  
  //UPDATE DROID APPS
  if(!lstDroidApps.isEmpty()) {
    update lstDroidApps;
  }
}

 Failure Message: "System.LimitException: Too many SOQL queries: 101", Failure Stack Trace: "Trigger.AppMembershipTrigger: line 38, column 1"

 

I've pasted the code and the error message above.  This would be much easier as a real Roll-Up Summary, but unfortunately we can't make this a Master-Detail Relationship because the Contact__c field is sometimes blank on the child object (App_Membership__c <--itself a junction object to App__c ).

 

The trigger works just fine in sandbox ``updating 4 fields on the parent records (Contact). However, when I deploy to production I get the error highlighted in red.

 

Is there a different/better way to do this that anyone knows of?

 

Is the SOQL Query limit trigger specific or org-wide?

 

I have a really basic trigger on the EmailMessage object that updates the Case Status when an incoming email is inserted. The trigger works just fine in testing and in my test class the System.assert passes. However, the trigger has 0% test coverage and I am not able to deploy to production.  Are there limitations with this object that I'm not aware of? Any idea why this is happening?


trigger updateCaseStatus on EmailMessage (before insert) {

    List<String> applicableStatus = new String[]{
        	'Support Agent Working - Resp Provided',
            'Resolved - Waiting for Customer Approval',
            'Waiting for Customer'};
    
    Set<Id> caseIds = new Set<Id>();
    
    for (EmailMessage em : Trigger.new)
    {
        // if it is an inbound email
        if (em.Incoming)
        {
            // add Case Id to caseIds set
            caseIds.add(em.ParentId);
        }
    }
    
    // query for Cases to update
    List<Case> casesToUpdate = [SELECT Id, Status FROM Case 
                                WHERE Id IN :caseIds AND Status IN :applicableStatus];
    
    if (!casesToUpdate.isEmpty())
    {
        for (Case c : casesToUpdate)
        {
            c.Status = 'Customer Response Provided';
        }
        update casesToUpdate;
    }    
}

@isTest
private class updateCaseStatus_Test{

    static void testInboundEmail() {
        // create test case
        Case testCase = new Case(
                Subject = 'Test case01',
                Priority = 'P1 - Emergency');
        testCase.Status = 'Waiting for Customer';
    	insert testCase;
        // System.debug('testCase: ' + testCase);
        
        // create test email message
        EmailMessage em = new EmailMessage(
        	Incoming = TRUE,
            FromAddress = 'someone@somewhere.com', 
            ToAddress= 'someone@nutanix.com', 
            Subject = 'Test email', 
            TextBody = 'Test',
            ParentId = testCase.Id);
        
        Test.startTest();
        insert em;
        // System.debug('em: ' + em);
        
        // query and system assert
        Case c = [SELECT Id, Status FROM Case WHERE Id = :testCase.Id LIMIT 1];
        System.assert(c.Status == 'Customer Response Provided');
        Test.stopTest();
    }
}


Does anyone know how I can get the Account Name and use it for the String Customer without doing a SOQL Query?

I'm trying to populate the String 'Customer' with Account Name, which is a look up from the Escalation__c object.

This is my Apex controller extension:

public with sharing class addCasesToEscalation{
    public Escalation__c theEsc {get;set;}
    public String searchString {get;set;}
    public Case[] shoppingCart {get;set;}
    public Case[] AvailableCases {get;set;}
    
    public String toSelect {get; set;}
    public String toUnselect {get; set;}
    public Decimal Total {get;set;}

    public Boolean overLimit {get;set;}
    public Id EscId {get;set;}
    public Id AcctId {get;set;}
   
    //using this for PDF report attachment
    public String pdfName {get;set;}
    public String Customer {get;set;}
 
    private Case[] forRemoval = new Case[]{};
    private Set<Case> clean = new Set<Case>();

    public addCasesToEscalation(ApexPages.StandardController controller) {

       
        // Get information about the Escalation being worked on
            system.debug(controller.getRecord());
            Escalation__c theEsc = (Escalation__c)controller.getRecord();
            EscId = theEsc.Id;
           
           
        // If cases were previously selected need to put them in the "selected cases" section to start with
        shoppingCart = [select Id, CaseNumber, Subject, Status, Priority, IsClosed, CreatedDate, Escalation__c from Case where Escalation__c=:EscId order by CreatedDate Desc];

            }
   

    public void updateAvailableList() {
   
        // We dynamically build a query string and exclude items already in the shopping cart
        String qString = 'select Id, CaseNumber, Subject, Status, Priority, CreatedDate, Escalation__c, IsClosed From Case WHERE AccountId = :AcctId';
       
        // note that we are looking for the search string entered by the user in the name OR description
        // modify this to search other fields if desired
        if(searchString!=null){
            qString+= ' and (Subject like \'%' + searchString + '%\' or CaseNumber like \'%' + searchString + '%\')';
        }
       
        Set<Id> selectedEntries = new Set<Id>();
        for(Case c : shoppingCart){
            selectedEntries.add(c.Id);
        }
       
        if(selectedEntries.size()>0){
            String tempFilter = ' and Id not in (';
            for(Id i : selectedEntries){
                tempFilter+= '\'' + (String)i + '\',';
            }
            String extraFilter = tempFilter.substring(0,tempFilter.length()-1);
            extraFilter+= ')';
           
            qString+= extraFilter;
        }
              
        qString+= ' order by CreatedDate Desc';
        qString+= ' limit 101';
       
        system.debug('qString:' +qString);       
        AvailableCases = database.query(qString);
       
        // We only display up to 100 results... if there are more then we let the user know (see vf page)
        if(AvailableCases.size()==101){
            AvailableCases.remove(100);
            overLimit = true;
        }
        else{
            overLimit=false;
        }
     
    }
   
    public void addToShoppingCart(){
   
        // This function runs when a user hits "select" button next to a product
   
        for(Case c : AvailableCases){
            if((String)c.Id==toSelect){
                c.Escalation__c = EscId;
                shoppingCart.add(c);
                break;
            }
        }
       
        updateAvailableList(); 
    }
   

public PageReference removeFromShoppingCart(){
   
        // This function runs when a user hits "remove" on an item in the "Selected Cases" section
   
        Integer count = 0;
        for(Case ce : shoppingCart){

            if((String)ce.Id==toUnselect){
               
                if(ce.Id!=null&&ce.Escalation__c != null){
                    ce.Escalation__c = null;
                    forRemoval.add(ce);}
                shoppingCart.remove(count);
                break;            
            }
            count++;
        }
       
        updateAvailableList();
       
        return null;
    }
   
    public PageReference onSave(){
   
        // If previously selected devices are now removed, we need to delete them
        if(forRemoval.size()>0)
            //this is a somewhat hackey way to clean the list just in case there are duplicate cases in the list
            clean.addAll(forRemoval);
            forRemoval.clear();
            forRemoval.addAll(clean);
            update(forRemoval);
   
        // Update cases in shoppingCart
            if(shoppingCart.size()>0)
                update(shoppingCart);
       
        // After save return the user to the Escalation
        return new PageReference('/' + EscId);
    }
   
    public PageReference onCancel(){

        // If user hits cancel we commit no changes and return them to the Escalation  
        return new PageReference('/' + EscId);
    }
   
   //pdf attach extension
    public PageReference savePdf() {

    PageReference pdf = Page.escalationReport;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',EscId);

    // create the new attachment
    Attachment attach = new Attachment();

    // the contents of the attachment from the pdf
    Blob body;

    try {

        // returns the output of the page as a PDF
        body = pdf.getContent();

    // need to pass unit test -- current bug   
    } catch (VisualforceException e) {
        body = Blob.valueOf('Something went wrong');
    }
       
    pdfName = Customer + ' escalation report as of '+String.valueOf(System.today());
    attach.Body = body;
    // add the user entered name
    attach.Name = pdfName;
    attach.IsPrivate = false;
    // attach the pdf to the account
    attach.ParentId = EscId;
    insert attach;

    // send the user to the account to view results
    return new PageReference('/'+EscId);

  }
   
}

This trigger I'm writing works well for individual records, but I know it's not going to work for bulk uploads/updates because I put 3 SOQL Queries inside the For Loop (o.0)

 

Can someone please advise me how to do this without putting the queries inside the loop? 

 

I'm trying to convert leads into existing Accounts (if there is a corresponding Account to conver them into)

 

trigger myLeadConvertTrigger on Lead(after insert, after update) {
	//Create an empty list of Leads to convert
    Database.LeadConvert[] leadsToConvert = new Database.LeadConvert[]{};
    //Find a Lead Status for Leads converted - note that this will take 1 value and only the first one that it finds
    LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
    
    //For Lead being updated or inserted
    for(Lead l : Trigger.new) {
        
        // if statement logic: Lead is Lead Source 'Sign Up' and was Invited and isn't converted yet
        if(l.LeadSource == 'Sign Up' && l.Was_Invited__c=='TRUE' && !l.isConverted) {
			
            //Create a list of Accounts where the Lead Company spelling matches the Account Name
    		List<Account> accountList = [SELECT Id, Name FROM Account WHERE Name = :l.Company LIMIT 1];//Need to figure out if there's a way to take this SOQL out of the for loop
             
            //Query AccountID via Invited to app 
            List<Apps__c> accountIdViaApp = [SELECT Account_Temp__c FROM Apps__c WHERE CritterAppID__c =:l.Invited_to_app__c LIMIT 1];
            
            //Query Account ID via Added by
            List<Contact> accountIdViaAddedBy = [SELECT AccountId FROM Contact WHERE CritterUserID__c =:l.Added_by__c LIMIT 1];
            
            //Create a new Lead Convert Record
            Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(l.id);
            lc.setConvertedStatus(convertStatus.MasterLabel); //set it to the status we retrieved
            lc.setDoNotCreateOpportunity(True); //do not create an opp
            
            //if accountIdViaApp is not empty
            if(!accountIdViaApp.isempty()){lc.setAccountId(accountIdViaApp[0].Account_Temp__c);}
                
            //else if accountIdViaAddedBy is not empty
            else if(!accountIdViaAddedBy.isempty()){lc.setAccountId(accountIdViaAddedBy[0].AccountId);}
            
            //else if accountList is not empty, set the Account Id
            else if(!accountList.isempty()){lc.setAccountId(accountList[0].Id);}
                        
            //add lc to the leadsToConvert list
            leadsToConvert.add(lc);
        }
    }
	//if the leadsToConvert list is not empty
    if(!leadsToConvert.isEmpty()) {
        //convert those Leads
        Database.convertLead(leadsToConvert );
    }
}
 

 

 

trigger AppMembershipTrigger on App_Membership__c (after delete, after insert, after update, after undelete) {
  
  Set<Id> stContactIds = new Set<Id>(); 
  for(App_Membership__c member :Trigger.isDelete ? Trigger.Old : Trigger.New) {
    if(member.Contact__c != null) {
      stContactIds.add(member.Contact__c);
    }
    if(Trigger.isUpdate && Trigger.oldMap.get(member.id).Contact__c != null) {
      stContactIds.add(Trigger.oldMap.get(member.id).Contact__c);
    }
  }
  
  //APP OWNER UPDATE
  List<Contact> lstContactOwner = [Select Id,(Select Id from App_Memberships__r where Role__c = 'App Owner' AND App__r.Current_MAU__c > 150) 
                                   FROM Contact 
                                   WHERE Id IN :stContactIds];
  for(Contact contact : lstContactOwner) {
    contact.Number_of_Apps_Owner__c = contact.App_Memberships__r.size();
  }
  
  //APP MEMBER UPDATE
  List<Contact> lstContactMember = [Select Id,(Select Id from App_Memberships__r where Role__c <> 'App Owner' AND App__r.Current_MAU__c > 150) 
                                   FROM Contact 
                                   WHERE Id IN :stContactIds];
  for(Contact contact : lstContactMember) {
    contact.Number_of_Apps_Member__c = contact.App_Memberships__r.size();
  }
  
  //IOS APPS UPDATE
  List<Contact> lstiOSApps = [Select Id,(Select Id from App_Memberships__r where Platform__c = 'ios') 
                                   FROM Contact 
                                   WHERE Id IN :stContactIds];
  for(Contact contact : lstiOSApps) {
    contact.Num_of_iOS_Apps__c = contact.App_Memberships__r.size();
  }
  
  //DROID APPS UPDATE
  List<Contact> lstDroidApps = [Select Id,(Select Id from App_Memberships__r where Platform__c = 'android') 
                                   FROM Contact 
                                   WHERE Id IN :stContactIds];
  for(Contact contact : lstDroidApps) {
    contact.Num_of_Droid_Apps__c = contact.App_Memberships__r.size();
  }
  
  //UPDATE CONTACT OWNER
  if(!lstContactOwner.isEmpty()) {
    update lstContactOwner;
  }
  
  //UPDATE CONTACT MEMBER
  if(!lstContactMember.isEmpty()) {
    update lstContactMember;
  }
  
  //UPDATE IOS APPS
  if(!lstiOSApps.isEmpty()) {
    update lstiOSApps;
  }
  
  //UPDATE DROID APPS
  if(!lstDroidApps.isEmpty()) {
    update lstDroidApps;
  }
}

 Failure Message: "System.LimitException: Too many SOQL queries: 101", Failure Stack Trace: "Trigger.AppMembershipTrigger: line 38, column 1"

 

I've pasted the code and the error message above.  This would be much easier as a real Roll-Up Summary, but unfortunately we can't make this a Master-Detail Relationship because the Contact__c field is sometimes blank on the child object (App_Membership__c <--itself a junction object to App__c ).

 

The trigger works just fine in sandbox ``updating 4 fields on the parent records (Contact). However, when I deploy to production I get the error highlighted in red.

 

Is there a different/better way to do this that anyone knows of?

 

Is the SOQL Query limit trigger specific or org-wide?

 

HI,

 

How to get current user's email ID in apex trigger? Please help.

 

 

Thanks,

Arunkumar

Hi,

 

I need to come up with a piece of code that will allow me to determine if the case owner is a queue or a user, The first things that come to my mind is to run a query on the owner and try to store the result to a user obect. If it faile therefore the case owner is a queue. I don't think this is a slick solution bo any means, so I am hoping someone can provide with a better suggestion.

 

Thank you.

  • March 30, 2011
  • Like
  • 0

I've written a trigger in my sandbox to copy the primary contact Role and ID values into 2 opportunity custom fields but it's not firing and I just cant figure out why.

 

Any help would be appreciated, I'm sure it's an oversight on my part.

 

Trigger PrimaryContactCopy on Opportunity(before insert,before update){
OpportunityContactRole Roles = new OpportunityContactRole();
for(Opportunity opp:Trigger.new){
Roles = [select Id,IsPrimary,ContactId, Role from OpportunityContactRole where IsPrimary=True AND opportunity.id=:opp.Id];
opp.Name__c = Roles.ContactId;
opp.Email__c = Roles.Role;
update opp;
 } 
}

 

  • December 13, 2010
  • Like
  • 0