• Moosecouture
  • NEWBIE
  • 10 Points
  • Member since 2012

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 9
    Replies
I think since I have two after update triggers.  I am thinking that they are some how conflicting and causing everything to run longer.  Does anybody know of a way to clean this code up so that these will not cause us to get close to our limits?  The First code is actually our attempt at resolving salesforce's issue with not giving access to trigger assignment rules natively from the webpage when creating a case using chatter actions or visual workflow.  The reason it is not just after insert like many I have seen out there is because sometimes we need the case to have child objects attached before we assign it to a queue.  We need this to be initiated at the time of when the case has been finished with information entry.

The Second code selection is going to show that we have a particular field that we added to the case and it looks to the account name and contact first name to make sure that they match the "C_S_Customer_Number__c" entered into the field so that it will return these values on the case.
trigger UpdateAssignmentGlobalActions on Case (after update, after insert) {
    try{
    List<Case> listCase = new List<Case>{};
    if(!ProcessorControl.inFutureContext){
    ProcessorControl.inFutureContext = true;
    List<Id> caseIds = new List<Id>{};
    AssignmentRule AR = new AssignmentRule();
    AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
    Database.DMLOptions dmlOpts = new Database.DMLOptions();
    dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;
    for(Case cse: Trigger.New)
    {
            caseIds.add(cse.Id);
    }
    

    for(Case cse: [Select Id, Assignment_Override__c from Case where Id in :caseIds])
    {
        If(cse.Assignment_Override__c == true)
        {
            cse.setOptions(dmlOpts);
            listCase.add(cse);
            cse.put('Assignment_Override__c',false);
        }
    }

    }
    update listCase;
    } catch(exception ex){}
}
@isTest
private class ChatterAssignmentRuleOverrideTest{
   static testMethod void verifyAssignmentOfCasesFromTrigger(){
    List<Case> cases = new List<Case>{};
    RecordType RecType = new RecordType ();
    RecType = [SELECT Id FROM RecordType WHERE SobjectType = 'Case' and IsActive = true and Name = 'CRM Request' LIMIT 1];    
    
    for(Integer i = 0; i < 200; i++){
        Case c = new Case(Subject = 'Test Case' + i, Issue_Type__c = 'CRM Issue', Assignment_Override__c = false, RecordType = RecType );
        cases.add(c);
    }
    insert Cases;
    
    List<Case> CaseList = new List<Case>{};
    For(Case Cse: [Select Id from Case where Assignment_Override__c = false])
    {
    cse.put('Assignment_Override__c',true);
    CaseList.add(cse);
    }
    test.startTest();
        
    update CaseList;
    test.stopTest();
        
    List<Case> insertedCases = [SELECT Subject, Description, OwnerId 
                                      FROM Case
                                      WHERE Id IN :cases];
        

    for(Case c : insertedCases){
      System.assertEquals(
      '00GE0000001VU9f' , 
        c.OwnerId);
    }
}
}
Here is the old code that seems to be igniting issues with limits.
trigger CaseAccountContact on Case (before insert, before update) {
try{
    if(!ProcessorControl.inFutureContext){
        ProcessorControl.inFutureContext = true;
        AccountContactHelper.findAccountContactByCustomerNumber(Trigger.new, false); 
    } else {
        ProcessorControl.inFutureContext = false;
        }
    }
    catch(Exception ex){}
}
public with sharing class AccountContactHelper {

    private static String customerNumber = 'C_S_Customer_Number__c'; 
    private static String CustomAccountField = 'Account__c'; 
    private static String CustomContactField = 'Contact__c';
    private static String StandardAccountField = 'AccountId';
    private static String StandardContactField = 'ContactId';

    public static boolean findAccountContactByCustomerNumber(List<SObject> records,boolean isCustom){

        Map<String,SObject> customerNumberMap   = new Map<String,SObject>();
        Map<Account,Contact> acctContacts       = new Map<Account,Contact>();
      
        String accountField = StandardAccountField;
        String contactField = StandardContactField;
        
        if(isCustom){
            accountField = CustomAccountField;
            contactField = CustomContactField;
        }
        

        for(SObject s : records){
            if(s.get(customerNumber) != null && s.get(customerNumber) != '')    
                customerNumberMap.put(String.valueof(s.get(customerNumber)),s);
        }
        
        if(customerNumberMap.size() == 0)
            return true; 
        
        for(Account a : [Select Id, Name, (Select Id, LastName, FirstName from Contacts) from Account]){
            if(a.Name.length() >= 5){ 
                acctContacts.put(a,null);
                for(Contact c : a.Contacts){
                    if(c.FirstName.length() >= 5 && (c.FirstName.subString(0,5) == a.Name.subString(0,5))) 
                        acctContacts.put(a,c); 
                }
            }
            
        }
        
        for(String s : customerNumberMap.keySet()){
            for(Account a : acctContacts.keySet())
                if(a.Name.subString(0,5)  == s){ 
                    customerNumberMap.get(s).put(accountField,a.Id);
                    if(acctContacts.get(a) != null) 
                        customerNumberMap.get(s).put(contactField,acctContacts.get(a).Id);                  
                    break; 
                }
        }

        return true;
    }


}
Here is the test class:
@isTest
private class TestAccountContactHelper {
    
    static testMethod void testCaseTrigger() {
        loadAccountContactData(); 
        List<Case> cases = new List<Case>(); 
        for(Integer i=0;i<200;i++){
            Case c = new Case(Status='New',Origin='Web',C_S_Customer_Number__c=+String.valueof(30000 + i));
            cases.add(c);
        }
        Test.startTest();
            insert cases; 
        Test.stopTest();
        cases = [Select Id, AccountId,ContactId,Account.Name,Contact.FirstName,C_S_Customer_Number__c from Case]; 
        system.assertEquals(200,cases.size()); 
        for(Case c : cases){
            system.assertEquals(c.C_S_Customer_Number__c,c.Account.Name.subString(0,5)); 
            system.assertEquals(c.C_S_Customer_Number__c,c.Contact.FirstName.subString(0,5)); 
        }
    }
    static void loadAccountContactData(){
        List<Account> accts = new List<Account>();
        List<Contact> cons  = new List<Contact>();
        for(Integer i=0;i<200;i++){
            Account a = new Account(Name=String.valueof(30000 + i));
            accts.add(a);
        }
        insert accts;
        for(Integer i=0;i<200;i++){
            Contact c = new Contact(LastName='Test',FirstName=String.valueof(30000 + i),AccountId=accts[i].Id);
            cons.add(c);
        }
        insert cons;
    }
}
Here were the issues we were having before adding "ProcessorControl.inFutureContext"
Maximum CPU time: 8783 out of 10000 ******* CLOSE TO LIMIT
Number of query rows: 26538 out of 50000 ******* CLOSE TO LIMIT
Here is where we still stand after this implementation
Maximum CPU time: 5911 out of 10000 ******* CLOSE TO LIMIT
Number of query rows: 17818 out of 50000
This implementation is taking less time but it should be working faster than this.

Thank you in advance,
Craig
When we try to get a visualforce page to be visible in our Community it says that the page is under construction and the worst part is that is references our other community.  Here is a Thread from an email regarding this.  I hope I can get some help on this.  Please and Thank you,

We need help with an error message that is coming up… And this is one of those weird ones again that we found.

We have a button called “Add New Items for Credit.” That when you select it should bring you to a visual force page. Now in the communicates environment when we select the button, it gives us an error message. Pay attention to the URL changes in the screen shots below. We need this fixed asap as this is a pretty big deal blocking roll out of communities.
User-added image

This is the error message… Notice the /ahold is missing now before the /apex.  Why??? Should not be like that. In addition, the error message is /APtea . That is a different community not yet published.

User-added image

This is what it should do and look like. Notice when we put the ahold in there as it should for the community, it works.

User-added image

I was asked to apply an email Alert on Certain Record Types that will go to a Reports To Contact for the Contact Submitting the Case due to the severity of cases like these.  Has anybody had this request with any Results?  I would figure it is similar to Escalation Rules but on the Account and Contact side of the case rather than the user side.

We want to be able to look for a product code and if the code is not currently available we would like to be able to add the Code with only one more button Click.  I have been looking everywhere for a solution similar to this and have not found it.

 

Detailed:

We sometimes have issues with our products and some come up more often than others.  We are looking to find a way to get these searched for and entered in Dynamically since the Items that are having issues currently should already be available while entering a case.  We are looking to accomplish this while in the Screen for Creating the cases as well.  Do you think this is possible?  If so can you point me in the correct direction.  I have never done anything quite this dynamic so I do not know where I would even start with this.

I have what I would think is a very simple task.  My Account Names all begin with a number followed with a space.  Is there any way to have this number load up into a Custom field every time that I open a case?  Maybe I am over reaching here.  We have a code developed that takes that Custom field and looks up the first five digits of an Account.  The Only reason I am asking for help with this is because I am assuming that the code that they developed is causing our Self-Service Portal to have errors thinking that the account is not filled because the Custom field is not filled.

 

I hope that this makes sense.

When we try to get a visualforce page to be visible in our Community it says that the page is under construction and the worst part is that is references our other community.  Here is a Thread from an email regarding this.  I hope I can get some help on this.  Please and Thank you,

We need help with an error message that is coming up… And this is one of those weird ones again that we found.

We have a button called “Add New Items for Credit.” That when you select it should bring you to a visual force page. Now in the communicates environment when we select the button, it gives us an error message. Pay attention to the URL changes in the screen shots below. We need this fixed asap as this is a pretty big deal blocking roll out of communities.
User-added image

This is the error message… Notice the /ahold is missing now before the /apex.  Why??? Should not be like that. In addition, the error message is /APtea . That is a different community not yet published.

User-added image

This is what it should do and look like. Notice when we put the ahold in there as it should for the community, it works.

User-added image

Thinking of enabling #Communities for your customer? Then be aware of the current #Gotcha that the default Apex Classes that are created when you enable your first Community do not ALL have code coverage >75%.

What this means:
You can enable Communities in Production, however as soon as you attempt to migrate anything from a sandbox into Production that triggers all tests to be run (doesn't have to be just code), your migration will fail as three of the classes only have 33%, 20% and 21%.

Let me repeat that, you might only be migrating a bunch of new custom fields and page layouts and the Change Set (or Eclipse/ANT) will fail.

I hit this problem this week in a go-live deployment so had to update Apex Classes to achieve average total code coverage >75% in order to proceed with our deployment.

The PM of Communities knows about the problem and advises he is looking at a fix, but in the meantime here are the four Apex Classes that need to be updated.

 

CommunitiesLandingControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that takes the user to the right start page based on credentials or lack thereof
 */
@IsTest public with sharing class CommunitiesLandingControllerTest {
  @IsTest(SeeAllData=true) public static void testCommunitiesLandingController() {
    // Instantiate a new controller with all parameters in the page
    CommunitiesLandingController controller = new CommunitiesLandingController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToStartPage();
  }
}

 

CommunitiesLoginControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that exposes the site login functionality
 */
@IsTest global with sharing class CommunitiesLoginControllerTest {
  @IsTest(SeeAllData=true) 
  global static void testCommunitiesLoginController () {
    CommunitiesLoginController controller = new CommunitiesLoginController ();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToAuthPage();
  }  
}

 

CommunitiesSelfRegControllerTest.cls

A few controller variables to set prior to calling the controller method for the original test method, followed by a couple of additional test methods for further coverage.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
@IsTest public with sharing class CommunitiesSelfRegControllerTest {
  @IsTest(SeeAllData=true) 
  public static void testCommunitiesSelfRegController() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = '8yhMsHDN&ituQgO$WO';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testInvalidPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = 'not the same';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testNullPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
}

 

CommunitiesSelfRegController.cls

A few additions to this class to set the Profile and Account Ids for portal user creation. Update the ProfileId value based on the "portal" license(s) (e.g., Customer Portal, Customer Community, etc) and set the AccountId to that of the Account you wish to use for self-registration. Note: this needs to be set even if you're not using self-registration so the class can be tested.

Plus some debug statements so I could see what was happening and needed to be tested.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
public with sharing class CommunitiesSelfRegController {

  public String firstName {get; set;}
  public String lastName {get; set;}
  public String email {get; set;}
  public String password {get; set {password = value == null ? value : value.trim(); } }
  public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
  public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
  
  public CommunitiesSelfRegController() {}
  
  private boolean isValidPassword() {
    return password == confirmPassword;
  }

  public PageReference registerUser() {
  
    // it's okay if password is null - we'll send the user a random password in that case
    if (!isValidPassword()) {
      System.debug(System.LoggingLevel.DEBUG, '## DEBUG: Password is invalid - returning null');
      ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
      ApexPages.addMessage(msg);
      return null;
    }  

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    //String profileId = ''; // To be filled in by customer.
    //String roleEnum = ''; // To be filled in by customer.
    //String accountId = ''; // To be filled in by customer.

    // Set this to your main Communities Profile API Name
    String profileApiName = 'PowerCustomerSuccess';
    String profileId = [SELECT Id FROM Profile WHERE UserType = :profileApiName LIMIT 1].Id;
    List<Account> accounts = [SELECT Id FROM Account LIMIT 1];
    System.assert(!accounts.isEmpty(), 'There must be at least one account in this environment!');
    String accountId = accounts[0].Id;
    
    String userName = email;

    User u = new User();
    u.Username = userName;
    u.Email = email;
    u.FirstName = firstName;
    u.LastName = lastName;
    u.CommunityNickname = communityNickname;
    u.ProfileId = profileId;
    
    String userId = Site.createPortalUser(u, accountId, password);
   
    if (userId != null) { 
      if (password != null && password.length() > 1) {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful and password ok - returning site.login');
        return Site.login(userName, password, null);
      }
      else {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful but password not ok - redirecting to self reg confirmation');
        PageReference page = System.Page.CommunitiesSelfRegConfirm;
        page.setRedirect(true);
        return page;
      }
    }
    System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation not successful - returning null');
    return null;
  }
}

 

 

Can someone help me understand how to access a picklist values from a picklist on a custom object in the cloud flow designer? It looks like I have recreate the picklist choices as Choices in flow, which I do not want to do from an on going management perspecitve. When I try Dynamic Choices it brings back record values and not just the picklist options. Thanks!

I am looking to create a Visualforce page that will serve as a data collection form on our website.  The user will ultimately be creating a contact record (linked to an existing account via a lookup) and then several child records (inquiry history, extra curricular interests, family relationships, etc.)  I would like the user to have the ability to create more than one of any of these child records during this process.

 

Visual:

 

Contact (1)
--Inquiry History (1)
--Extra Curricular Interests (Many)
--Family Relationships (Many)
--Test Scores (Many)

 

1)  Is this feasible?

2) What technique is best suited for this type of action?

 

I would like to send an email to a non-case-owner each time a new case comment is added.

 

On the force.com discussion board I found a workaround for the problem of generating an email alert from a workflow from case comments. Implementing all the steps suggested by jgreene (his post), I got stuck with the last step 

where the workflow action is created to notify the user of the new case comment: 

 

Add a new workflow action to the above rule:
-Description: "Notify account team of new case comment"
-Email Template: "Case Comment added - notify account team"
-Recipient Type: Account Team
-Recipients:
  Account Team: Primary Sales Engineer
  Account Team: Secondary Sales Engineer

 

My problem is: the person to who I want to send the notification email to can differ for every case. Each case created in our SF environment gets assigned to a specific "case solver", based on the "case type" chosen from a picklist. So the recipient of the email alert depends on the case type. In total there are 8 different case types, thus 8 different possible mail receivers.

 

Ideally, in the "recipients"-field of the email alert workflow action I should be able to add the field "case type" (which is then linked to the case solver and the email address of that user), but that's not an option.

 

Anyone has a suggestion how to tackle this problem?

 

 

Any help is greatly appreciated!

 

I'm attempting to create my first VF page. It is a line-item entry form that will allow a user to enter multiple child records (Lit_Order_Detail__c) before clicking save. Right now, I'm opening the VF page from a custom button on the parent (Lit_Order__c). However, when the page opens, the lookup field for the parent is not populated - so the user has to click the lookup to select the parent from Lit_Order__c. Is there a way to pass the parent id of the previous page to the new child records on the VF page?

 

My Visualforce page:

 

 

<apex:page standardController="Lit_Order_Detail__c" extensions="OrderEntry"> <apex:form > <apex:pageBlock title="Sales Literature Orders Quick Entry" > <apex:pageBlockButtons > <apex:commandButton value="Save" action="{!save}" rerender="error" /> </apex:pageBlockButtons> <apex:pageBlockTable value="{!ords}" var="a" id="table"> <apex:column headerValue="Order ID"> <apex:inputField value="{!a.Lit_Order__c}"/> </apex:column> <apex:column headerValue="Order Detail ID"> <apex:inputField value="{!a.Name}"/> </apex:column> <apex:column headerValue="Request"> <apex:inputField value="{!a.Literature_Request__c}"/> </apex:column> <apex:column headerValue="Quantity"> <apex:inputField value="{!a.Quantity__c}"/> </apex:column> </apex:pageBlockTable> <apex:pageblockButtons location="bottom"> <div style="text-align:right;margin-right:30px;font-weight:bold;"> <apex:commandLink value="Add Row" action="{!addRow}" rerender="table,error" immediate="true" /> &nbsp;|&nbsp;&nbsp; <apex:commandLink value="Remove Row" action="{!removeRow}" rerender="table,error" immediate="true" /> </div> </apex:pageblockButtons> </apex:pageBlock> </apex:form> </apex:page>

 

 

 

 

My Apex class:

 

 

public class OrderEntry { public List<Lit_Order_Detail__c> ords {get; set;} public OrderEntry(ApexPages.StandardController myController) { ords = new List<Lit_Order_Detail__c>(); ords.add(New Lit_Order_Detail__c());} public void addrow() { ords.add(new Lit_Order_Detail__c());} public void removerow(){ Integer i = ords.size(); ords.remove(i-1);} public PageReference save() { insert ords; PageReference home = new PageReference('/home/home.jsp'); home.setRedirect(true); return home; }}

 

Thank you!

 

 

  • February 06, 2009
  • Like
  • 0