• Michael Pugliese
  • NEWBIE
  • 30 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 1
    Replies

I'm using the following code samples to create a custom pre-chat form: 
https://developer.salesforce.com/docs/atlas.en-us.snapins_web_dev.meta/snapins_web_dev/snapins_web_lightning_components_prechat_sample_aura.htm

I'm trying to figure out how to write a very simple validation function (just to prevent null fields). I have this so far:

function validateFields(fields) {
var fieldsAreValid = true;

fields.forEach(field) {
fieldsAreValid = fieldsAreValid && field.value; 
}

return fieldsAreValid;
}



but have not been succsful in implementing it. Any resources/help would be very much appreciated!

Thanks,

Michael 

Hello! 

We have an existing web-to-case visualforce form hosted on a Force.com site. Part of the apex class includes setting the DML options, specifically "EmailHeader.triggerAutoResponseEmail"
// Specify DML options to ensure the assignment rules are executed
        Database.DMLOptions dmlOpts = new Database.DMLOptions();
        dmlOpts.AssignmentRuleHeader.useDefaultRule = true;
        dmlOpts.EmailHeader.triggerAutoResponseEmail = true;
        WebCase.setOptions(dmlOpts);

        INSERT WebCase;

Even though we are setting auto response as true, we have been unable to trigger the case auto-respose emails using this form. 

This is in a sandbox environement, email deliverability = all (auto-response rules work with the SFDC standard HTML form), and nothing sends for existing contacts or when only web-email is provided. I know I can set up a trigger/workflow for this specifically, but would prefer not to make an exception for a single form. 

Any tips or assistance would be appreciated!
We are working on a new (custom) web-to-case form. Part of the requirement is for it to auto-lookup contacts based on provided email and assign existing contacts to the case. To achieve this we added this lookup:
List<Contact> cnt = [Select Id, Account.Id from Contact where Email =: WebCase.SuppliedEmail LIMIT 4];
        if((!cnt.isEmpty()) && (cnt.size() == 1)){
            WebCase.ContactId = cnt.get(0).Id;
            WebCase.AccountId = cnt.get(0).Account.Id;
After adding these lines of code, we get an "Authorization Required" error on the site after submitting a case - debug logs seem to pin it on a case trigger that's supposed to count the number of cases of a specific record type:
trigger countCasesOnAccount on Case (after insert, after update) {
    List<Case> lstCase = [select id, AccountId from Case where id in: trigger.newmap.keyset()];
    set<Id> sAccId = new set<Id>();
    for(Case cs: lstCase){
        if(cs.AccountId != null){
            sAccId.add(cs.AccountId);
        }
    }
    if(sAccId != null && sAccId.size() > 0){
        List<Account> lstAccount = [select id, Open_At_Risk_Cases__c, (select id from Cases where status != 'Closed' AND RecordTypeID = '012d0000000hDP1') from Account where id in: sAccId];
        if(lstAccount.size() > 0){
            for(Account acc: lstAccount){
                acc.Open_At_Risk_Cases__c = acc.Cases.size();
            }
            
            update lstAccount;
        }
    }
}

The guest user has access to all fields required to execute this, but it still fails. Just wondering:

1) What are the options to have this process work around this trigger, or do we need to remove this trigger entirely?
2) If there's a better way to have the contact lookup happen (like with the native web-to-case functionality) 
I have been working on a visual flow, launched from an account page to create cases. As an admin, I have no issues running it. However, some users are generating this error when the case is created at the end of the flow:

This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: CaseTrigger: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 5000V000018MPzLQAW; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: [] Class.CaseServices.generateUniqueBase64IDs: line 58, column 1 Trigger.CaseTrigger: line 15, column 1. For details, see API Exceptions.

Here's the method from Case Services: 
public static void generateUniqueBase64IDs(List<Case> caseList)
    {
        List<Case> casesToUpdate = new List<Case>();
        for(Case inputCase: caseList)
        {
            Case c = new Case(id = inputCase.id);
            c.Base64ID__c = EncodingUtil.base64Encode(Blob.valueOf(c.id));
            casesToUpdate.add(c);
        }
        
        update casesToUpdate;
    }
And here's the case trigger:
trigger CaseTrigger on Case (after insert, before update, after update) 
{
  System.debug('\n\nGenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) = '+GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY)+'\n\n');
    if(Trigger.isBefore && Trigger.isUpdate)
    {
        if(GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) == '1')
        {
          CaseServices.addCaseTrackerAndCaseHistoryEntries(Trigger.newMap, Trigger.oldMap);
        }
    }
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert)
        {
            CaseServices.generateUniqueBase64IDs(Trigger.new);
        }
        else if(Trigger.isUpdate)
        {
            if(GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) == '1')
            {
                //CaseServices.deleteCasesCreatedFromEmailWithoutThreadID(Trigger.newMap);
                CaseServices.closeAndUpdateChildCases(Trigger.newMap, Trigger.oldMap);
            }
        }
    }
    //CaseServices.closeAndUpdateChildCases(Trigger.newMap, Trigger.oldMap);
}

The user is able to create an identical case outside of a flow. 

Any ideas here? 

-Michael 
 
Recently we have been seeing this error:
Apex script unhandled exception by user/organization:
 
Visualforce Page: /apex/Case 
caused by: System.LimitException: Too many SOQL queries: 101
 
Class.AccountServices.rollupAssetAnnualSubscription: line 403, column 1
Trigger.AccountTrigger: line 11, column 1

The method is a rollup function designed to sum the asset values for Locations/Facilities (record type) to the parent Client (record type):
public static void rollupAssetAnnualSubscription(List<Account> accs){
      
      Set<Id> accIds = new Set<Id>();
      List<Account> accsToUpdate = new List<Account>();
      for(Account a : accs){
       if(a.ParentId != null && a.RecordTypeId == recordTypesNameMap.get(Constants.ACCOUNT_RECORD_TYPE_FACILITY).ID)
        accIds.add(a.ParentId);     
      }
      System.debug('**********accIds' + accIds);
      //A sub query has a limit of 200 records so I do not use one to query the related objects 
      //in place of a sub query I use a query of the objects based on the affected accounts
      Map<Id,Decimal> accountObjectSizeMap = new Map<Id,Decimal>();
      for(Account ob : [SELECT ParentId,Asset_Annual_Subscriptions__c FROM Account WHERE ParentId IN :accIds]){
       if(accountObjectSizeMap.containsKey(ob.ParentId)){
            Decimal i = accountObjectSizeMap.get(ob.ParentId);
            i = i + ob.Asset_Annual_Subscriptions__c;
            accountObjectSizeMap.put(ob.ParentId,i);
       }
       else
            accountObjectSizeMap.put(ob.ParentId,ob.Asset_Annual_Subscriptions__c);
      }
      System.debug('************accMap' + accountObjectSizeMap);
      //then query the accounts and set the count to the map value
      for(Account a : [SELECT Id,Locations_Asset_Annual_Subscriptions__c FROM Account WHERE Id IN :accIds]){
       a.Locations_Asset_Annual_Subscriptions__c = accountObjectSizeMap.get(a.Id);
       accsToUpdate.add(a);
      }

The issue seems to be that we now have some location record type accounts that have parents that are also locations (a recent change in protocol), so when this method tries to run it results in the SOQL query limit error. I'm trying to figure out if it's easier to just scrap this rollup entirely, or if it's possible to adjust to allow for locations to rollup to locations (or just prevent this error). 

Any info/direction would be much appreciated!

Thanks, 

Michael Pugliese
 

We're having an issue with a custom Web2Case visualforce page and apex class. When cases are submitted, an error is displayed:
"List has no rows for assignment to SObject", this error triggers a custom label indicating the case wasn't submitted. After testing, it looks like the case is created regardless of the error, but it's confusing our users who assume it was not. 
public with sharing class Web2CaseCont {
    
    public Case c { get; set; }
    public Boolean isSubmitted {get; private set;}
    public String msg {get; private set;}
    public String isDebug {get; private set;} 
    public Attachment att {get {
        if (att == null)
            att = new Attachment();
        return att;
    }
    set;}
         
    public Web2CaseCont() {
        this.isSubmitted = false;
        c = new Case();
        AssignFromParameters();
    }
    
    public PageReference submitCase() {
        try{
            c.SuppliedName = c.SuppliedFirstName__c + ' ' + c.SuppliedLastName__c;
            List<Contact> cnt = [Select Id, Account.Id from Contact where Email =: c.SuppliedEmail LIMIT 10];
            if((!cnt.isEmpty()) && (cnt.size() == 1)){
                c.ContactId = cnt.get(0).Id;
                c.AccountId = cnt.get(0).Account.Id;
            }
            
            // Specify DML options to ensure the assignment rules are executed
            Database.DMLOptions dmlOpts = new Database.DMLOptions();
            dmlOpts.assignmentRuleHeader.useDefaultRule = true;
            dmlOpts.EmailHeader.triggerAutoResponseEmail = true;
            c.setOptions(dmlOpts);
            
            INSERT c;
            this.isSubmitted = true;
            case c2 = [select CaseNumber from case where Id =: c.Id];
            msg = System.label.WebCaseSuccess + ' ' + c2.CaseNumber+'.  ';
            AddAttachment();
        }catch (Exception e){
          ApexPages.addMessages(e);
          msg = System.label.WebCaseFailure;
          return null;
        }
        return null;     
    }
    
    public void AssignFromParameters(){
        Map<string,string> pageParameters = ApexPages.currentPage().getParameters();
        c.SuppliedCompany = pageParameters.get('co');
        c.Product_Line__c = pageParameters.get('pline');
        c.Origin = pageParameters.get('origin');
        isDebug = pageParameters.get('debug');
        if ((isDebug == null) || (isDebug.toLowerCase() != 'true'))
            isDebug = 'false';
        if(c.Origin == null)
            c.Origin = 'Web';
    }
    
    public void AddAttachment(){
        if((att.Name !=null) && (c.Id != null)){
            att.ParentId = c.Id;
            insert(att);
            msg = msg + '<br/> The attachment "' + att.Name + '" uploaded successfully.';
            att = null; //set to null or viewstate will error.  
            }  
    }
}

I can see where the error is displayed, but I have limited apex knowledge so having trouble figuring out what's causing the issue. Any information would be a great start!

Thanks, 

Michael Pugliese
Hi, 

I recently made a minor change to an older Apex Class - essentially I updated a query to exclude certain picklist values (added set and excluded in query):
Set<String> ExcludedVerticals = new Set<String>{'Vertical1', 'Vertical2'};//sets verticals to be excluded from NPS surveys
        Set<ID> accountIdsToSendEmailTo = new Set<ID>();
        for(Contract ctrct: [Select ID, AccountID, Subscription_Start_Date__c
                             from Contract 
                             where AccountID in: accountIDs
                             and Contract_Status__c =: 'Active'
                             and Subscription_Start_Date__c !=: null
                             and Account.Vertical__c not in: ExcludedVerticals])
This class sends out NPS survey based on contract information. In order for me to save this on Sandbox I had to delete the existing scheduled job. 

My questions is how do I recreate the scheduled job to execute the class? I know it's not as important on Sandbox, but I'd like to know the exact process in preperation for moving to production. 

I'll also add that I'm not very experienced in development, but slowly making by way through small projects like this so any and all help would be appreciated!

We do have existing Test and Schedule classes that reference the class I edited. 

Thanks, 
Michael 
I have been working on a visual flow, launched from an account page to create cases. As an admin, I have no issues running it. However, some users are generating this error when the case is created at the end of the flow:

This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: CaseTrigger: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 5000V000018MPzLQAW; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: [] Class.CaseServices.generateUniqueBase64IDs: line 58, column 1 Trigger.CaseTrigger: line 15, column 1. For details, see API Exceptions.

Here's the method from Case Services: 
public static void generateUniqueBase64IDs(List<Case> caseList)
    {
        List<Case> casesToUpdate = new List<Case>();
        for(Case inputCase: caseList)
        {
            Case c = new Case(id = inputCase.id);
            c.Base64ID__c = EncodingUtil.base64Encode(Blob.valueOf(c.id));
            casesToUpdate.add(c);
        }
        
        update casesToUpdate;
    }
And here's the case trigger:
trigger CaseTrigger on Case (after insert, before update, after update) 
{
  System.debug('\n\nGenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) = '+GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY)+'\n\n');
    if(Trigger.isBefore && Trigger.isUpdate)
    {
        if(GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) == '1')
        {
          CaseServices.addCaseTrackerAndCaseHistoryEntries(Trigger.newMap, Trigger.oldMap);
        }
    }
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert)
        {
            CaseServices.generateUniqueBase64IDs(Trigger.new);
        }
        else if(Trigger.isUpdate)
        {
            if(GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) == '1')
            {
                //CaseServices.deleteCasesCreatedFromEmailWithoutThreadID(Trigger.newMap);
                CaseServices.closeAndUpdateChildCases(Trigger.newMap, Trigger.oldMap);
            }
        }
    }
    //CaseServices.closeAndUpdateChildCases(Trigger.newMap, Trigger.oldMap);
}

The user is able to create an identical case outside of a flow. 

Any ideas here? 

-Michael