• jill.longo
  • NEWBIE
  • 15 Points
  • Member since 2013
  • ReSources IT(Publicis Groupe)

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 7
    Replies
I need to create a VF page that is editable for users to log infomation which needs to be shown in a specific format. I plan to create a custom object to allow for multiple records to be created to track this information. The category field would be a picklist option and these records would relate to an Account record. The fields would beed to be able to be edited inline as well. I believe this can be done, but not 100% positive.

Example of layout
Getting a Dml exception error when running a test class.

Error Message System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Account, original object: User: []
Stack Trace Class.TaskTriggerTest.getAccount: line 141, column 1
Class.TaskTriggerTest.testTask5: line 116, column 1
 
Also getting a errror at line 9, column 1, line 38, column 1, line 60, column 1, line 88, column 1


Here's the Trigger:

@isTest
private class TaskTriggerTest {
   
    // test the task Count
    static testMethod void testTask() {
       
        Test.startTest();
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
       
        system.debug('Test Class - Program: '+ prog.Id);
       
        Case c = getCase(user.Id, ac,prog);
       
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        system.debug('Test Class - Case: '+ c.Id);
        system.debug('Test Class - User: '+ user.Id);
        system.debug('Test Class - Case Program: '+ c.Program__c);
       
        mapTask = getTasks(c.Id,user.Id);
        system.debug('Test Class - mapTask = ' + mapTask.size());
       
        CaseAutomation.updateCaseTaskCount(mapTask,'In Progress','Insert');
        Test.stopTest();
    }
   
   
    // test the task Count
    static testMethod void testTask2() {
       
        Test.startTest();
       
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
        Case c = getCase(user.Id, ac,prog);
       
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        mapTask = getTasks(c.Id,user.Id);
       
        CaseAutomation.updateCaseTaskCount(mapTask,'In Progress','Delete');
        CaseAutomation.rollupTotalTasktime(mapTask);
       
        Test.stopTest();
    }
   
      // test the task Count
    static testMethod void testTask3() {
       
        Test.startTest();
       
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
        Case c = getCase(user.Id, ac,prog);
       
        List<Task> newTask = new List<Task>();
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        mapTask = getTasks(c.Id,user.Id);
       
        for(Task task : mapTask.values()){
            newTask.add(task);
        }
       
        CaseAutomation.updateCaseTaskCount(mapTask,'Completed','');
        CaseAutomation.sendEmailToTeam(newTask,newTask);
        CaseAutomation.addCaseComment(newTask,'Completed');
        CaseAutomation.rollupTotalTasktime(mapTask);
       
        Test.stopTest();
    }
   
    // test the task Count
    static testMethod void testTask4() {
        Test.startTest();
       
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
        Case c = getCase(user.Id, ac,prog);
       
        List<Task> newTask = new List<Task>();
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        mapTask = getTasks(c.Id,user.Id);
       
        for(Task task : mapTask.values()){
            newTask.add(task);
        }
       
        CaseAutomation.updateCaseTaskCount(mapTask,'In Progress','');
        CaseAutomation.addCaseComment(newTask,'Completed');
        CaseAutomation.rollupTotalTasktime(mapTask);
       
        Test.stopTest();
    }
   
      // test the task Count
    static testMethod void testTask5() {
       
        Test.startTest();
       
        User user = UserNewTestData();
        Account ac = getAccount('Test Account');
       
        Program__c prog = getProgram(ac);
        getAccountTeam(prog);
        Case c = getCase(user.Id, ac,prog);
       
        List<Task> newTask = new List<Task>();
        Map<Id, Task> mapTask = new Map<Id,Task>();
       
        mapTask = getTasks(c.Id,user.Id);
       
        for(Task task : mapTask.values()){
            newTask.add(task);
        }
       
        delete newTask;
       
       
        Test.stopTest();
    }
   
   
      // get an account for the parameter passed
    static Account getAccount(String accountName) {
        Account ac = new Account(Name = accountName, website='www.hotmail.com',Account_Status__c = 'Prospect',BillingStreet= '1',BillingCity = '1', BillingState = '1', BillingPostalCode = '12345');
        insert ac;
        return ac;     
    }
   
    static Program__c getProgram(Account ac){
        Program__c prog = new Program__c(
            Name = 'Test Program',
            Account__c = ac.Id,
            Platform__c = 'Marin',
            Website__c = 'www.google.com'
        );
       
        insert prog;       
        return prog;
    }
   
    static void getAccountTeam(Program__c prog){
        Account_Team__c acTeam = new Account_Team__c(
            Program__c = prog.Id,
            Date_Assigned__c = Date.parse('2/25/2015'),
            o__c = 'AM'        
        );
       
        insert acTeam;
       
    }
   
     //test data for Case   
    static Case getCase(Id userId, Account ac,Program__c prog){
       
        Case newCase = new Case(
            AccountId = ac.Id,
            Business_Unit__c = 'Paid Search',
            Request__c = 'New Campaign',
            Sub_Request__c = 'New Campaign',
            Assigned_To__c =  userId,
            Due_Date__c = Date.parse('2/25/2015'),
            Total_of_Closed_Task_s__c = 2,
            Total_of_Open_Task_s__c = 2,
            Total_of_Overdue_Task_s__c = 0,
            Program__c = prog.Id
        );
       
        insert newCase;
        return newCase;
    }
   
    static Map<Id,Task> getTasks(Id caseId,Id userId){
       
        List<Task> lstTask = new List<Task>();
        Task task = null;
        Map<Id,Task> mapTask = new Map<Id,Task>();
       
       
        for(Integer counter =0;counter<=5;counter++){
            task = new Task();
           
            task.WhatId = caseId;
            task.Subject = 'Test Task';
           
            if(counter<=3)
                task.Status = 'In Progress';
            else
                task.Status = 'Completed';
               
            task.Priority = 'Normal';
            //task.IsRecurrence = false;
            task.OwnerId = userId;
           
            lstTask.add(task);
        }
       
        insert lstTask;
       
        for(Task newTask: lstTask){
           
            mapTask.put(newTask.Id,newTask);
        }
       
        return mapTask;
    }
   
     static User UserNewTestData(){
        Profile profile = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
               
       
        User usr = new User();
        usr.LastName = 'test user';
        usr.Alias = 'tst';
        usr.Email = 'testuer@domain.com';
        usr.UserName = 'test_xyz1234@test.com' ;
        usr.CommunityNickname = 'tests';
        usr.UserRoleId = userInfo.getUserRoleId();
        usr.TimeZoneSidKey = 'America/Los_Angeles';
        usr.ProfileId = profile.Id ;
        usr.LocaleSidKey = 'en_US' ;
        usr.EmailEncodingKey = 'ISO-8859-1';
        usr.LanguageLocaleKey = 'en_US';      
        usr.isActive = true;
       
        insert usr;
        return usr;
    }

}
I need to create a table that contains only contact records where a custome field called Escalation Contact is checked. The table should contain the Name of the contact and phone number. I'm having trouble with my IF statement and don't know if i have it placed in the correct location.

<apex:page standardController="Account">
<apex:pageBlock >
    <apex:pageBlockTable value="{! account.contacts}" var="item">
        <apex:column value=" {IF({!item.Escalation_Contact__c},"{!item.name}", "")}"/>
         <apex column value="{! item.phone}"/>  
           
    </apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
Has anyone created a VF page that aggregates Account data into a single view that would allow the Account Owner to generate a report/PDF? We have found that using a report doesn't provide a valuable view of an account, especially when we are pulling data from multiple objects. Ideally the user would click a button on the Account that says generate Account Overview.  I'm looking for code that would give me an idea of how to start this and then add in our custom objects.
I need to create a table that contains only contact records where a custome field called Escalation Contact is checked. The table should contain the Name of the contact and phone number. I'm having trouble with my IF statement and don't know if i have it placed in the correct location.

<apex:page standardController="Account">
<apex:pageBlock >
    <apex:pageBlockTable value="{! account.contacts}" var="item">
        <apex:column value=" {IF({!item.Escalation_Contact__c},"{!item.name}", "")}"/>
         <apex column value="{! item.phone}"/>  
           
    </apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

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;
  }
}