• Holly Havelka 10
  • NEWBIE
  • 200 Points
  • Member since 2017
  • Salesforce Administrator
  • Breakthrough Collaborative

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 26
    Questions
  • 62
    Replies
Hi all,

I have the following custom lightning component, but it is coming up with the following error: Unknown controller action 'getOpps'.

component:
<aura:component controller="AcctOppsController" implements="flexipage:availableForRecordHome,force:hasRecordId">
    <aura:attribute name="mydata" type="OpportunityContactRole[]"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="currentRecordId" type="Id" />
    <aura:handler name="init" value="{!this }" action="{! c.doInit }"/>
    <div style="height: 300px">
        <lightning:datatable
                keyField="id"
                data="{! v.mydata }"
                columns="{! v.mycolumns }"
                hideCheckboxColumn="true"/>
    </div>
</aura:component>
controller:
({
    doInit: function (cmp, event, helper) {
        cmp.set('v.mycolumns', [
            {label: 'Opportunity Name', fieldName: 'opportunityId', type: 'text'},
            {label: 'Contact Name', fieldName: 'contact', type: 'text'},
            {label: 'Role', fieldName: 'role', type: 'text'},
            {label: 'Amount', fieldName: 'amount', type: 'currency'}
        ]);
        
        var fetchData = {
            opportunityId: "opportunityId",
            contact : "Contact.Name",
            role : "Role",
            amount : "Opportunity.Amount"
        };

        helper.fetchData(cmp,fetchData);
    }
})
helper:
({
    fetchData : function(cmp) {
        var recordId =  cmp.get("v.recordId");
        var action = cmp.get("c.getOpps");
        action.setParams({ "currentRecordId" : recordId });
        action.setCallback(this, $A.getCallback(function (response) {
            var state = response.getState();
            if (state ==="SUCCESS") {
                cmp.set("v.mydata", response.getReturnValue());
            } else if (state === "ERROR") {
                var errors = response.getError();
                console.error(errors);
            }
        }
                                               ));
        $A.enqueueAction(action);
    }
})
apex controller:
public with sharing class AcctOppsController{
@AuraEnabled
public String currentRecordId {get;set;}

    public AcctOppsController(ApexPages.StandardController controller) {
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
    }
    
    @AuraEnabled    
    public List<OpportunityContactRole> getOpps() {
        List<OpportunityContactRole> oppresults = [SELECT Contact.name, Role, OpportunityId, Opportunity.Amount, Opportunity.StageName, Opportunity.Type FROM OpportunityContactRole WHERE contact.accountid=:currentRecordId];
        return oppresults;
        }
}

Any thoughts on what I am missing?


 

Hi all, 
I have the below apex sharing trigger, but am struggling to get code coverage (currently at 44%):
trigger AffiliationMakePublicContactTrigger on npe5__Affiliation__c (after insert, after update, before delete) {
 
    // Get the Account Name Details
    Set<Id> AcctId = new Set<Id>();
    List<Account> AccountLists = new List<Account>();
    Map<Id,String> AccountNameMap = new Map<Id,String>();
	
    if (!Trigger.isDelete) {
		List<npe5__Affiliation__c> affiliations = [select Id, npe5__Organization__c, npe5__Organization__r.Id, Make_Public__c, npe5__Contact__r.Id from npe5__Affiliation__c where Id IN: Trigger.newMap.keyset()];
		for(npe5__Affiliation__c aff : affiliations)
		{
		 
		 if(aff.npe5__Organization__r != null)
		 {
			AcctId.add(aff.npe5__Organization__r.Id);
		 }

		}
		 
		 if(AcctId.size() > 0)
		 {
			 AccountLists  = [select Id,name from Account where Id IN: AcctId];
		 }

		for(Account acc :AccountLists  )
		{
			AccountNameMap.put(acc.id,acc.Name);
		}
		
		// Get the Group Details
		List<Group> groups = [SELECT Email,Id,Name FROM Group];

		Map<String,Id> GroupMap = new MAp<String,Id>();
		for( Group grp:groups)
		{
			if(grp.Name != null && grp.Name != '')
			{
				GroupMap.put(grp.Name,grp.Id);
			}
		}
	  
	  // inserting new records
	  if (Trigger.isInsert) {
				 
		List<ContactShare> sharesToCreate = new List<ContactShare>();

		
		for (npe5__Affiliation__c affiliation : affiliations) {
			
		  if (affiliation.Make_Public__c == true) 
		  {

			// create the new share for group
			ContactShare cs = new ContactShare();
			cs.ContactAccessLevel = 'Edit';
			cs.ContactId = affiliation.npe5__Contact__r.Id;        
			system.debug(cs.ContactId);
			if(GroupMap.containsKey(AccountNameMap.get(affiliation.npe5__Organization__r.Id)))
					cs.UserOrGroupId = GroupMap.get(AccountNameMap.get(affiliation.npe5__Organization__r.Id));   
			sharesToCreate.add(cs);

		  }
		}

		// do the DML to create shares
		if (!sharesToCreate.isEmpty())
		  insert sharesToCreate;

	  // updating existing records
	  } else if (Trigger.isUpdate) {

		List<ContactShare> sharesToCreate = new List<ContactShare>();
		List<ID> shareIdsToDelete = new List<ID>();

		for (npe5__Affiliation__c affiliation : affiliations) {

		  // if the record was public but is now private -- delete the existing share
		  if (Trigger.oldMap.get(affiliation.Id).Make_Public__c == true && affiliation.Make_Public__c == false) {
			shareIdsToDelete.add(affiliation.npe5__Contact__r.Id);

		  // if the record was private but now is public -- create the new share for the group
		  } else if (Trigger.oldMap.get(affiliation.Id).Make_Public__c == false && affiliation.Make_Public__c == true) {
			
			// create the new share with read/write access
			ContactShare cs = new ContactShare();
			cs.ContactAccessLevel = 'Edit';
			cs.ContactId = affiliation.npe5__Contact__r.Id;
			if(GroupMap.containsKey(AccountNameMap.get(affiliation.npe5__Organization__r.Id)))
					cs.UserOrGroupId =  GroupMap.get(AccountNameMap.get(affiliation.npe5__Organization__r.Id));   
			sharesToCreate.add(cs);

		  }

		}

		// do the DML to delete shares
		if (!shareIdsToDelete.isEmpty())
		  delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = 'Manual'];

		// do the DML to create shares
		if (!sharesToCreate.isEmpty())
		  insert sharesToCreate;

	  }
  }
  else if (Trigger.isDelete) {

    List<ID> shareIdsToDelete = new List<ID>();

	List<npe5__Affiliation__c> affiliations = [select Id, npe5__Organization__c, npe5__Organization__r.Id, Make_Public__c, npe5__Contact__r.Id from npe5__Affiliation__c where Id IN: Trigger.oldMap.keyset()];
    for (npe5__Affiliation__c affiliation : affiliations) {
        shareIdsToDelete.add(affiliation.npe5__Contact__r.Id);
        system.debug(shareIdsToDelete);
    }

    // do the DML to delete shares
    if (!shareIdsToDelete.isEmpty())
      delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = 'Manual'];
  }

}
Here is my test class:
@isTest
private class TestAffiliationMakePublicContactTrigger {

    // test that newly inserted records marked as pubic=true have corresponding shares created
    static testMethod void testAddShares() {
    
    Account acct = new Account(name='Breakthrough Birmingham');
        insert acct;
    Contact c = new Contact(AccountId=acct.Id, lastname='testing', firstname='apex');
        insert c;
    
    //Create Public Group
    Group gp            = new Group();
    gp.Name             = 'Breakthrough Birmingham';
    gp.DeveloperName    = 'Breakthrough_Birmingham';
    gp.Type             = 'Regular';
    insert gp;
    
    ContactShare testShare = new ContactShare();
    testShare.ContactAccessLevel = 'Edit';
    testShare.ContactId = c.Id;        
	testShare.UserOrGroupId = gp.Id;
    insert testShare;
    
    Set<ID> affiliationIds = new Set<ID>();
    List<npe5__Affiliation__c> affiliations = new List<npe5__Affiliation__c>();
    
    for (npe5__Affiliation__c aff : affiliations)
        affiliations.add(new npe5__Affiliation__c(npe5__Organization__c=acct.Id,Make_Public__c=true,npe5__Contact__c=c.Id));
		insert affiliations;
        
    for (npe5__Affiliation__c a : affiliations)
      affiliationIds.add(a.npe5__Contact__r.id);
        
    // assert that 1 share was created
    List<ContactShare> shares = [select id from ContactShare where 
      ContactId IN :affiliationIds and RowCause = 'Manual'];
    System.assertEquals(shares.size(),1);
    }

    // insert records and switch them from public = true to public = false
    static testMethod void testUpdateAffiliations() {

    Account acct = new Account(name='Breakthrough Birmingham');
        insert acct;
    Contact c = new Contact(AccountId=acct.Id, lastname='testing', firstname='apex');
        insert c;
        
    Set<ID> affiliationIds = new Set<ID>();
    List<npe5__Affiliation__c> affiliations = new List<npe5__Affiliation__c>();
    
    for (npe5__Affiliation__c aff : affiliations)
        affiliations.add(new npe5__Affiliation__c(npe5__Organization__c=acct.Id,Make_Public__c=false,npe5__Contact__c=c.Id));
		insert affiliations;
        
    for (npe5__Affiliation__c a : affiliations)
      affiliationIds.add(a.npe5__Contact__r.id);
        
    // assert that 0 shares exist
    List<ContactShare> shares = [select id from ContactShare where 
      ContactId IN :affiliationIds and RowCause = 'Manual'];
    System.assertEquals(shares.size(),0);
    
    for (npe5__Affiliation__c aff : affiliations)
      aff.Make_Public__c = true;

    update affiliations;

    // assert that 1 share was created
    shares = [select id from ContactShare where ContactId IN :affiliationIds and RowCause = 'Manual'];
    System.assertEquals(shares.size(),1);

    for (npe5__Affiliation__c aff : affiliations)
      aff.Make_Public__c = false;

    update affiliations;

    // assert that 0 shares exist
    shares = [select id from ContactShare where ContactId IN :affiliationIds and RowCause = 'Manual'];
    System.assertEquals(shares.size(),0);

    }
}

 
Hi all,

I have the below trigger, which is throwing this error: First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Contact, User/Group]: [Contact, User/Group]: Trigger.AffiliationMakePublicContactTrigger: line 64, column 1
trigger AffiliationMakePublicContactTrigger on npe5__Affiliation__c (before insert) {
 
    // Get the Account Name Details
    Set<Id> AcctId = new Set<Id>();
    List<Account> AccountLists = new List<Account>();
    Map<Id,String> AccountNameMap = new Map<Id,String>();
    
    for(npe5__Affiliation__c aff : trigger.new)
    {
     
     if(aff.npe5__Organization__r != null)
     {
        AcctId.add(aff.npe5__Organization__r.Id);
     }

    }
     
     if(AcctId.size() > 0)
     {
         AccountLists  = [select Id,name from Account where Id IN: AcctId];
     }

    for(Account acc :AccountLists  )
    {
        AccountNameMap.put(acc.id,acc.Name);
    }
    
    // Get the Group Details
    List<Group> groups = [SELECT Email,Id,Name FROM Group];

    Map<String,Id> GroupMap = new MAp<String,Id>();
    for( Group grp:groups)
    {
    	if(grp.Name != null && grp.Name != '')
    	{
        	GroupMap.put(grp.Name,grp.Id);
    	}
    }
  
  // inserting new records
  if (Trigger.isInsert) {
             
    List<ContactShare> sharesToCreate = new List<ContactShare>();

    for (npe5__Affiliation__c affiliation : Trigger.new) {
        
      if (affiliation.Make_Public__c == true) 
      {

        // create the new share for group
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = affiliation.npe5__Contact__r.Id;        
        system.debug(cs.ContactId);
        if(GroupMap.containsKey(AccountNameMap.get(affiliation.npe5__Organization__r.Id)))
                cs.UserOrGroupId = GroupMap.get(AccountNameMap.get(affiliation.npe5__Organization__r.Id));   
        sharesToCreate.add(cs);

      }
    }

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  // updating existing records
  } else if (Trigger.isUpdate) {

    List<ContactShare> sharesToCreate = new List<ContactShare>();
    List<ID> shareIdsToDelete = new List<ID>();

    for (npe5__Affiliation__c affiliation : Trigger.new) {

      // if the record was public but is now private -- delete the existing share
      if (Trigger.oldMap.get(affiliation.Id).Make_Public__c == true && affiliation.Make_Public__c == false) {
        shareIdsToDelete.add(affiliation.Id);

      // if the record was private but now is public -- create the new share for the group
      } else if (Trigger.oldMap.get(affiliation.Id).Make_Public__c == false && affiliation.Make_Public__c == true) {
        
        // create the new share with read/write access
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = affiliation.npe5__Contact__r.Id;
        if(GroupMap.containsKey(AccountNameMap.get(affiliation.npe5__Organization__r.Id)))
                cs.UserOrGroupId =  GroupMap.get(AccountNameMap.get(affiliation.npe5__Organization__r.Id));   
        sharesToCreate.add(cs);

      }

    }

    // do the DML to delete shares
    if (!shareIdsToDelete.isEmpty())
      delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = 'Manual'];

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  }

}
I have the affiliation object (from NPSP), and it creates the following records with these fields: organization affiliation (account lookup), contact (contact lookup) and 'make public' field. 
I want to share the contact (contact lookup) from the affiliation record with a specified public group whether that happens on insert or on update.  
Any thoughts on what I am missing?
 
Hi All,

I have the below trigger, and what I want to do is pull in the name of the group based on a field on the contact record where the after insert/after update is taking place.  The field is an account lookup field on contact and is named: Acct__c.  I want this to happen dynamically vs. having to hard code the name of the group.
trigger ContactMakePublicTrigger on Contact (after insert, after update) {
  
  ID groupId = [select id, Name from Group where Name = 'Cincinati User'].id;
    
  // inserting new records
  if (Trigger.isInsert) {
	         
    List<ContactShare> sharesToCreate = new List<ContactShare>();

    for (Contact contact : Trigger.new) {
        
      if (contact.Make_Public__c == true) {

        // create the new share for group
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = contact.Id;
        cs.UserOrGroupId =  groupId;
        sharesToCreate.add(cs);

      }
    }

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  // updating existing records
  } else if (Trigger.isUpdate) {

    List<ContactShare> sharesToCreate = new List<ContactShare>();
    List<ID> shareIdsToDelete = new List<ID>();

    for (Contact contact : Trigger.new) {

      // if the record was public but is now private -- delete the existing share
      if (Trigger.oldMap.get(contact.id).Make_Public__c == true && contact.Make_Public__c == false) {
        shareIdsToDelete.add(contact.id);

      // if the record was private but now is public -- create the new share for the group
      } else if (Trigger.oldMap.get(contact.id).Make_Public__c == false && contact.Make_Public__c == true) {
        
        // create the new share with read/write access
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = contact.Id;
        cs.UserOrGroupId =  groupId;
        sharesToCreate.add(cs);

      }

    }

    // do the DML to delete shares
    if (!shareIdsToDelete.isEmpty())
      delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = 'Manual'];

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  }

}
Any thoughts on how to rework the trigger to get the name of the lookup field dynamically?
 
Hi all,

I have the following Service Class:
public class INDICATOR_Service {
    public static List<String> getFieldsToQueryForObject(String objName){
        Set<String> targetFields = new Set<String>();
        for(Indicator_Badge__mdt i: [SELECT Related_Field__r.QualifiedApiName FROM Indicator_Badge__mdt WHERE Object__r.QualifiedApiName = :objName]){
            targetFields.add(i.Related_Field__r.QualifiedApiName);
        }
        return new List<String>(targetFields);
    }
    public static List<Indicator> getIndicatorBadgesForObject(SObject sobj){
        List<Indicator> recordIndicators = new List<Indicator>();
        for(Indicator_Badge__mdt indicator: [SELECT MasterLabel, Badge_Color__c, Comparison_Value__c, Comparison_Type__c,
                                        Badge_Icon_Name__c, Related_Field__r.QualifiedApiName
                                    FROM Indicator_Badge__mdt WHERE Object__r.QualifiedApiName = :sobj.getSObjectType().getDescribe().getName()]){
            recordIndicators.add(evaluateIndicator(indicator, sobj));
        }
        return recordIndicators;
    }
    private static Indicator evaluateIndicator(Indicator_Badge__mdt i, SObject sobj){
        Object field = sobj.get(i.Related_Field__r.QualifiedApiName);
        Boolean isEnabled = false;
        if(i.Comparison_Type__c == 'Use Boolean Value of Field'){
        isEnabled = (Boolean)field;
        } else if(i.Comparison_Type__c == 'Contains'){
            isEnabled = (String.valueOf(field)).contains(i.Comparison_Value__c);
        } else if(i.Comparison_Type__c == 'Not Blank or Null'){
            isEnabled = String.isNotBlank(String.valueOf(field));
        } else if(i.Comparison_Type__c == 'Blank or Null'){
            isEnabled = String.isBlank(String.valueOf(field));
        } else if(i.Comparison_Type__c == 'Greater or Equal'){
            isEnabled = (Decimal)field >= Decimal.valueOf(i.Comparison_Value__c);
        } else if(i.Comparison_Type__c == 'Less or Equal'){
            isEnabled = (Decimal)field <= Decimal.valueOf(i.Comparison_Value__c);
        }
        if(isEnabled){
            return new Indicator(i.Badge_Icon_Name__c, i.Badge_Color__c, i.MasterLabel);
        }else{
            return null;
        }
    }
    //inner class, creating our 'Indicator' object and attributes
    public class Indicator{
        //first, the attributes:
        @AuraEnabled
        public String icon {get; set;}
        @AuraEnabled
        public String color {get; set;}
        @AuraEnabled
        public String label {get; set;}
        //then, our object:
        public Indicator(String icon, String color, String label){
          this.icon = icon;
          this.color = color;
          this.label = label;
      }
    }
}
Here is my test class:
@isTest
public class INDICATOR_ServiceTest {
    @isTest static void testgetFieldsToQueryForObject(){
        system.assert(!INDICATOR_Service.getFieldsToQueryForObject('Account').isEmpty());
  }
    
    @isTest static void testgetIndicatorBadgesForObject(){
        Contact testContact = new Contact();
        system.assert(!INDICATOR_Service.getIndicatorBadgesForObject(testContact).isEmpty());
    }
}
I am getting 50% code coverage.  Any thoughts on increasing this code coverage?
 
Hi all,

I am struggling to write a test class for the below controller:
public class INDICATOR_Controller {
    private static SObject sobj;
    @AuraEnabled
    public static String getSObjectLabel(String sObjName){
        String label = Schema.getGlobalDescribe().get(sObjName).getDescribe().getLabel();
        return label;
    }
    @AuraEnabled
    public static List<INDICATOR_Service.Indicator> getIndicators(String recId, String objectName){
        getSObject(recId, objectName);
        if(sobj != NULL){
            List<INDICATOR_Service.Indicator> indicators = INDICATOR_Service.getIndicatorBadgesForObject(sobj);
            return indicators;
        } else{
            return null;
        }
    }
    public static void getSObject(String recId, String objectName){
        List<String> fNames = INDICATOR_Service.getFieldsToQueryForObject(objectName);
        if(fNames.size() > 0){
            String query = 'SELECT Id,'+ String.join(fNames,',')+' FROM '+ objectName +' WHERE Id =\''+ recId +'\' LIMIT 1';
            List<SObject> results = Database.query(query);
            if(results.size() == 1){
                sobj = results[0];
            }
        }
    }
}
Any thoughts on where to begin?  
 
Hi all,

I am trying to create a simple visualforce page, which I can then display in a lightning component on lightning page layout.  The issue I am running into is that part of the in-line edit is being cut-off on my page.  See below image.
In Line Edit
Here is my visualforce page code:
<apex:page standardController="Contact" lightningStylesheets="true">
  <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" lang="en">
    <head>
      <meta charset="utf-8" />
      <meta http-equiv="x-ua-compatible" content="ie=edge" />
      <title>Contact Details</title>
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      
      <apex:slds />
    </head>
    <body>
      <div class="slds-scope">
          <apex:form styleClass="slds-form-element slds-size_2-of-2" >
              <apex:pageBlock >
                  <apex:pageBlockSection title="Basic">
                      <apex:pageBlockSectionItem >
                          <apex:outputlabel value="Name: "/>
                          <apex:outputField value="{!Contact.Name}">
                              <apex:inlineEditSupport event="ondblClick"/>
                          </apex:outputField>
                      </apex:pageBlockSectionItem>
                      
                      <apex:pageBlockSectionItem >
                          <apex:outputlabel value="Account Name: " />
                          <apex:outputField value="{!Contact.AccountID}">
                              <apex:inlineEditSupport event="ondblClick"/>
                          </apex:outputField>
                      </apex:pageBlockSectionItem>
                      
                      <apex:pageBlockSectionItem >
                          <apex:outputlabel value="Title: " />
                          <apex:outputField value="{!Contact.Title}">
                              <apex:inlineEditSupport event="ondblClick"/>
                          </apex:outputField>
                      </apex:pageBlockSectionItem>
                      
                      <apex:pageBlockSectionItem >
                          <apex:outputlabel value="Email: " />
                          <apex:outputField value="{!Contact.Email}">
                              <apex:inlineEditSupport event="ondblClick"/>
                          </apex:outputField>
                      </apex:pageBlockSectionItem>
                  </apex:pageBlockSection>
              </apex:pageBlock>
          </apex:form>
      </div>
    </body>
  </html>
</apex:page>
Any thoughts on how to fix this page?
Displaying Chatter Group Files on VisualForce Page Help With Limits
Hi all,

I am running into an issue where I am only able to show (5) Chatter Groups with their respective files at a time on my visualforce page.  

Here is my controller:
public class BTInstructionalTrainingController {
        
    public Map<String, List<ContentVersion>> groupResourceMap {get; set;}
    
    public Set<String> collaborationGroups {get; set;}
    
    public BTInstructionalTrainingController(){
        
        Network portal = [SELECT Id FROM Network WHERE Name = 'Breakthrough Portal'];
        
        List<CollaborationGroupFeed> groupFeeds = [SELECT RelatedRecordId, Title, Parent.Name, NetworkScope FROM CollaborationGroupFeed WHERE Parent.Name LIKE '%#BITLibrary' ORDER By Parent.Name, Title ASC];
        
        Map<String, List<Id>> groupResouceIdMap = new Map<String, List<Id>>();
        
        List<Id> allResourcesIds = new List<Id>();
        
        for (CollaborationGroupFeed feed : groupFeeds) {
            
            if (feed.NetworkScope != portal.Id || Test.isRunningTest()){
                feed.Parent.Name = feed.Parent.Name.replace('#BITLibrary', '');
                
                List<Id> relatedRecordsList = new List<Id>();
                
                if (groupResouceIdMap.get(feed.Parent.Name) != null){
                    relatedRecordsList = groupResouceIdMap.get(feed.Parent.Name);
                }
                
                relatedRecordsList.add(feed.RelatedRecordId);
                groupResouceIdMap.put(feed.Parent.Name, relatedRecordsList);
                allResourcesIds.add(feed.RelatedRecordId);
            }
            
        }
        
        groupResourceMap = new Map<String, List<ContentVersion>>();
        
        Map<Id, ContentVersion> allResources = new Map<Id, ContentVersion>([SELECT Title, Description, CreatedBy.Name, LastModifiedDate, ContentSize, FileType FROM ContentVersion WHERE Id IN :allResourcesIds]);
        
        collaborationGroups = groupResouceIdMap.keySet();
        
        for(String collaborationGroup : collaborationGroups) {
            
            List<ContentVersion> resourcesList = new List<ContentVersion>();
            
            for(Id resourceId : groupResouceIdMap.get(collaborationGroup)) {
                resourcesList.add(allResources.get(resourceId));
            }
            
            groupResourceMap.put(collaborationGroup, resourcesList);
        }
        
    }
}


Here is my visualforce page:
<apex:page controller="BTInstructionalTrainingController">
    
    <style>
        .tableTitle {
            color: #0082C8;
            font-size: 18px;
            font-weight: bold;
            font-family: Clarendon;
        }
        .resourceTable {
            background: none !important;
            border: 0px !important;
        }
        .tableHeader {
            border: none !important;
        }
        .headerRow.tableHeader {
            border-bottom: 2px solid #B2B2B3 !important;
            background: none !important;
        }
        .apexDefaultPageBlock {
            border: 0px !important;
            background: none !important;
        }
        .dataCell {
            border: none !important;
        }
        .data2Col {
            border: none !important;
        }
    </style>
    
    <apex:pageBlock >
    <br/>
    
    <br/>
    </apex:pageBlock>
    
    <apex:pageBlock >
        <apex:pageBlockSection collapsible="false" columns="1">
            <apex:repeat value="{!collaborationGroups}" var="group">
                <apex:pageBlockSectionItem >
                    <apex:pageBlockTable value="{!groupResourceMap[group]}" var="res" headerClass="tableHeader" styleClass="resourceTable">
                        <apex:facet name="header">
                            <apex:outputText value="{!group}" styleClass="tableTitle"/>
                        </apex:facet>
                        <apex:column headerValue="Title" width="30%">
                            <apex:outputLink value="/{!res.Id}" style="color: #000 !important; text-decoration: underline; font-family: Arial,Helvetica,sans-serif; font-weight: normal;">{!res.Title}</apex:outputLink>
                        </apex:column>
                        <apex:column headerValue="Description" value="{!res.Description}" width="40%">
                        </apex:column>
                        <apex:column headerValue="File Type" value="{!res.FileType}" width="15%">
                        </apex:column>
                    </apex:pageBlockTable>
                </apex:pageBlockSectionItem>
                <br/>
            </apex:repeat>
        </apex:pageBlockSection>
    </apex:pageBlock>
    
</apex:page>


Any thoughts on why I am restricted to just (5) Chatter Groups?

Thanks in advance for any help!
Hi all,

I need help figuring out why my visual flow is failing.  Here is the email error information:

Flow Interview Details
Interview Label: Sharing Contact with Breakthrough Role Associated BT Site 2/28/2018 11:37 AM
Current User: Holly Havelka (00533000004LpP0)
Start time: 2/28/2018 11:37 AM
Duration: 0 seconds

How the Interview Started
Holly Havelka (00533000004LpP0) started the flow interview.
Some of this flow's variables were set when the interview started.
varAssociatedBTSiteName = Atlanta
varAssociatedContact = 0031D000003HipNQAS

RECORD QUERY: Lookup_Associated_BT_Site_Role_ID
Find one UserRole record where:
DeveloperName Equals {!varAssociatedBTSiteName} (Atlanta)
Result
Successfully found record.
{!varAssociatedAffiliateSite} = 00E40000000kkg8EAA

RECORD CREATE: Share_Contact_Record_with_Associated_Affiliate_Site
Create one ContactShare record where:
ContactAccessLevel = Read
ContactId = {!varAssociatedContact} (0031D000003HipNQAS)
RowCause = Manual
UserOrGroupId = {!varAssociatedAffiliateSite} (00E40000000kkg8EAA)
Result
Failed to create record.

Error Occurred: This error occurred when the flow tried to create records: FIELD_INTEGRITY_EXCEPTION: User/Group ID: id value of incorrect type: 00E40000000kkg8EAA.
Hi all,

I am working on a business solution with the following requirements:
  • End User needs to be able to view the contact record of a household account
  • Org Wide Defaults are set to 'private' on the contact records
  • End users should not be able to view ALL contacts
  • End users should be able to view some contact records WHEN a junction object between contact and accounts, 'Role Object', has a record with a lookup to an Account with the same company name as the user who is logged in. 
Does anyone have any ideas on how to approach a potential solution for the above requirements?  I am running into a wall on providing a solution.

Any thoughts?
Hi All,

I have a Batch Apex Job that gets dynamically submitted when a user clicks a custom button on a record details page.  

The issue I am having is that the job is getting stuck in 'Holding' until 11:00 pm, same day, vs. going next when resources are available.  I am not sure where to even look to see why this issue is occuring.  I have a UAT environment that is set up exactly like production, but I am not having this issue in UAT.  The batch apex job is firing just fine.  

Any thoughts on where I can look for this issue?
Hi All,

I have this autocomplete function on the college account field.  See below screenshot.

User-added image

What I want to do is force the user to select one of the accounts listed in the drop-down, if an account name matches what they have typed into the box.  Right now the logic will allow them to create another account in the database, even though it shows one exists in the drop-down, if they just click the 'save' button on the page.  

Here is the controller:
public class ProfileSubmitController {

    public List<SelectOption> genders { get; set; }
    public List<SelectOption> ethnicity { get; set; }
    public List<SelectOption> eligibleToWorkUS { get; set; }
    public List<SelectOption> freeOrReducedLunch { get; set; }
    public List<SelectOption> grantPellRecipient { get; set; }
    public List<SelectOption> parentsHighestEducation { get; set; }
    public List<SelectOption> states { get; set; }
    //public List<SelectOption> collegeList { get; set; }
    public List<SelectOption> primaryPhoneTypes { get; set; }
    public List<SelectOption> primaryAddressTypes { get; set; }
    public List<SelectOption> otherPhoneTypes { get; set; }
    public List<SelectOption> otherAddressTypes { get; set; }
    public List<SelectOption> majorCategory { get; set; }
    public List<SelectOption> secondMajorCategory { get; set; }
    public List<SelectOption> minorCategory { get; set; }

    public ProfileSubmitController() {
        
        eligibleToWorkUS = new List<SelectOption>();
        Schema.DescribeFieldResult fieldResult = Application__c.Eligible_to_work_in_US__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            eligibleToWorkUS.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        genders = new List<SelectOption>();
        genders.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.Gender__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            genders.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        ethnicity = new List<SelectOption>();
        ethnicity.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.Ethnicity__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            ethnicity.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        freeOrReducedLunch = new List<SelectOption>();
        fieldResult = Application__c.GAP_Grant_Free_or_Reduced_Lunch__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            freeOrReducedLunch.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        grantPellRecipient = new List<SelectOption>();
        fieldResult = Application__c.Gap_Pell_Grant_Recipient__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            grantPellRecipient.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        parentsHighestEducation = new List<SelectOption>();
        fieldResult = Application__c.Parents_Highest_Level_of_education__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            parentsHighestEducation.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        Map<String, State_List__c> stateList = State_List__c.getAll();
        states = new List<SelectOption>();
        states.add(new SelectOption('', 'Please Select...'));
        List<SelectOption> statesAux = new List<SelectOption>();
        for (String stateName : stateList.keySet()){
            statesAux.add(new SelectOption(stateList.get(stateName).Abbreviation__c, stateName));
        }
        statesAux.sort();
        states.addAll(statesAux);
/*
        collegeList = new List<SelectOption>();
        collegeList.add(new SelectOption('', 'Please Select...'));
        List<Account> sitesList = [SELECT Name FROM Account WHERE RecordType.Name = 'Colleges & Universities'];
        for (Account acc : sitesList){
            if (acc.Name != null){
                collegeList.add(new SelectOption(acc.Id, acc.Name));
            }
        }
*/
        primaryPhoneTypes = new List<SelectOption>();
        primaryPhoneTypes.add(new SelectOption('', 'Please Select...'));
        primaryPhoneTypes.add(new SelectOption('Home', 'Home'));
        primaryPhoneTypes.add(new SelectOption('Cell', 'Cell'));
        primaryPhoneTypes.add(new SelectOption('Office 1', 'Office'));
        primaryPhoneTypes.add(new SelectOption('Other', 'Other'));

        primaryAddressTypes = new List<SelectOption>();
        primaryAddressTypes.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.npe01__Primary_Address_Type__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            primaryAddressTypes.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        otherPhoneTypes = new List<SelectOption>();
        otherPhoneTypes.add(new SelectOption('', 'Please Select...'));
        otherPhoneTypes.add(new SelectOption('Home', 'Home'));
        otherPhoneTypes.add(new SelectOption('Cell', 'Cell'));
        otherPhoneTypes.add(new SelectOption('Office', 'Office'));
        otherPhoneTypes.add(new SelectOption('Other', 'Other'));

        otherAddressTypes = new List<SelectOption>();
        otherAddressTypes.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.Other_Address_Type__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            otherAddressTypes.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        majorCategory = new List<SelectOption>();
        majorCategory.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.College_Major_Category_new__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            majorCategory.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        secondMajorCategory = new List<SelectOption>();
        secondMajorCategory.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.College_Major_Category_2nd_Major__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            secondMajorCategory.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        minorCategory = new List<SelectOption>();
        minorCategory.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.College_Minor_Category__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            minorCategory.add(new SelectOption(f.getLabel(), f.getValue()));
        }

    }

    @RemoteAction
    public static Boolean savePageOne(String application, String myContact){
        List<Breakthrough_Application_Settings__c> settings = [SELECT Name, 
                                                                    Regular_Deadline__c,
                                                                    Backdoor_Application_Open__c
                                                            FROM Breakthrough_Application_Settings__c 
                                                            WHERE Active__c = true LIMIT 1];
        Datetime backdoorOpen = Datetime.newInstance(settings[0].Backdoor_Application_Open__c, Time.newInstance(0,0,0,0));
        Boolean backdoorApplicationOpen = Datetime.now() >= backdoorOpen;   
        
        Contact cont = (Contact)JSON.deserialize(myContact, Contact.Class);
        Application__c app = (Application__c)JSON.deserialize(application, Application__c.Class);

        if (String.isBlank(cont.College__c) && String.isNotBlank(cont.Other_College__c)){
            RecordType collegeRecordType = [SELECT Id FROM RecordType WHERE Name = 'Colleges & Universities'];
            Account newCollege = new Account(RecordTypeId = collegeRecordType.Id, Name = cont.Other_College__c);
            insert newCollege;
            cont.College__c = newCollege.Id;
        }

        cont.Other_College__c = '';

        update cont;
        app.Page_1_Status__c = 'Complete';

        if (backdoorApplicationOpen) {
            RecordType recordType = [select Name from RecordType where Name = 'Backdoor' and SObjectType = 'Application__c'];
            app.RecordTypeId = recordType.Id;
            app.X2nd_City_Preference__c = null;
            app.X2nd_City_Housing_Needed__c = null;
            app.X3rd_City_Preference__c = null;
            app.X3rd_City_Housing_Needed__c = null;
        }
        
        try {
            update app;
        } catch (Exception e) {
            app.Page_1_Status__c = 'In Progress';
            update app;
        }
        Datetime regularDeadline = Datetime.newInstance(settings[0].Regular_Deadline__c, Time.newInstance(0,0,0,0)).addDays(1);
        return ((Datetime.now() >= regularDeadline) && !backdoorApplicationOpen);
        
    }

    @RemoteAction
    public static List<Result> getSearchResults(String searchTerm) {
        List<Result> resultsList = new List<Result>();
        
        searchTerm = searchTerm + '*';
        
        List<List<sObject>> searchResults = [FIND :searchTerm IN ALL FIELDS RETURNING Account(Id, Name, BillingCity, BillingState WHERE RecordType.Name = 'Colleges & Universities')];

        if(!searchResults.isEmpty()) {
            for(List<sObject> objects : searchResults) {
                for(sObject obj : objects) {
                    Account a = (Account)obj;
                    Result r = new Result(a.Name, a.Id, a.BillingCity, a.BillingState);
                    resultsList.add(r);
                }
            }
        }
        
        return resultsList;
    }
    
    public class Result {
        public String name {get; set;}
        public String recordId {get; set;}
        public String BillingCity {get; set;}
        public String BillingState {get; set;}    
        public Result(String name, String recordId, String BillingCity, String BillingState) {
            this.name = name;
            this.recordId = recordId;
            this.BillingCity = BillingCity;
            this.BillingState = BillingState;
        }
    }

}



Here is the section of the component that does the remotesearch for the account names:
function doRemoteSearch() {
            var searchTerm = document.getElementsByClassName('searchBox')[0].value;
            
            if(searchTerm.length >= 2) {
                Visualforce.remoting.Manager.invokeAction(
                    '{!$RemoteAction.ProfileSubmitController.getSearchResults}',
                    searchTerm,
                    function(result, event) {
                        if(event.status) {

                            var tbody = document.getElementById('resultsTableBody');
                            var tbodyRows = document.getElementById('resultsTableBody').rows.length;

                            tbody.innerHTML = '';

                            var resultLength = result.length;
                            if (resultLength != 0){
                                document.getElementsByClassName('resultsTable')[0].style.display = '';
                                
                                for(var i = 0; i < resultLength; i++) {
                                        
                                        var wrapperTbody = document.createElement('tbody');
                                        //add id and name to data attributes of the tbody element
                                        wrapperTbody.dataset.id = result[i].recordId;
                                        wrapperTbody.dataset.name = result[i].name;
                                        wrapperTbody.addEventListener("click", fillWithSelectedCollege);
                                        
                                        var tr = document.createElement('tr');
                                        var td = tr.appendChild(document.createElement('td'));
                                        
                                        //add name
                                        tr = document.createElement('tr');
                                        td = tr.appendChild(document.createElement('td'));
                                        td.innerHTML = result[i].name;
                                        
                                        wrapperTbody.appendChild(tr);
                                        //add city and state
                                        tr = document.createElement('tr');
                                        td = tr.appendChild(document.createElement('td'));
                                        td.innerHTML = '<span style="font-size:0.8em;font-style:italic">'
                                        + result[i].BillingCity + ',' + result[i].BillingState +
                                        '</span>';

                                        wrapperTbody.appendChild(tr);

                                        tbody.appendChild(wrapperTbody);


                                }
                            } else {
                                document.getElementsByClassName('resultsTable')[0].style.display = 'none';
                            }
                        } else {
                            alert('An error occurred');
                        }
                    },
                    {escape: true}
                );
            } else {
                document.getElementsByClassName('resultsTable')[0].style.display = 'none';
            }
        }

<!-- ************************************ UNDERGRADUATE COLLEGE SUBSECTION ************************************ -->
			<apex:outputPanel styleClass="undergraduate" style="display: none">
				<apex:pageBlockSection id="sndsubSection" columns="1" collapsible="false">
					<apex:facet name="header">
						<apex:outputText styleClass="subSectionHeader" value="Undergraduate College"/>
					</apex:facet>

					<apex:panelGrid columns="1">
						<apex:outputLabel styleClass="customLabel">Undergraduate College <span class="reqMark">*</span></apex:outputLabel>
						<apex:inputText value="{!actualContact.Other_College__c}" maxlength="255" size="80" label="" onkeyup="doRemoteSearch()" styleClass="searchBox" id="otherCollege"/>
						<apex:inputText value="{!actualContact.College__c}" styleClass="accId" style="display: none" id="college"/>
					</apex:panelGrid>      
					<table class="resultsTable" style="display: none">
						<tbody id="resultsTableBody">
						</tbody>
					</table>

					<apex:panelGrid columns="2">
						<apex:panelGrid columns="1">
							<apex:outputLabel styleClass="customLabel">Graduation Year <span class="reqMark">*</span></apex:outputLabel>
							<apex:inputText value="{!actualContact.College_Grad_Year__c}" size="20" label="" maxlength="4" styleClass="numberInput" id="collegeGradYear" onchange="checkMinLength(this, 4)"/>
						</apex:panelGrid>

						<apex:panelGrid columns="1">
							<apex:outputLabel styleClass="customLabel">Cumulative Undergraduate GPA <span class="reqMark">*</span></apex:outputLabel>
							<apex:inputText value="{!actualContact.College_GPA__c}" size="5" label="" maxlength="3" html-pattern="\d{1}\.\d{1}" onchange="checkCollegeGPA(this)" id="collegeGPA"/>
							<apex:outputLabel style="color: red; font-weight: bold; display: none;" id="collegeGPAErrorLabel"/>
						</apex:panelGrid>
					</apex:panelGrid>
Any thoughts on how to add this requirement into the functionality?
Hi all,

Looking for help on an issue with my controller and visualforce page.

The issue I am having is that the picklist value for 'Interested Technologies' is returning weird results vs. just the name of the account.
User-added image

Here is my controller:
public with sharing class ContactSearchController {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}
  // the collection of accounts to display
  public Id selectedAccId{get;set;}

  public Boolean IsEmpty {get; set;} 

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public ContactSearchController() {
    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.name != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String firstName = Apexpages.currentPage().getParameters().get('firstname');
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String technology = Apexpages.currentPage().getParameters().get('technology');

    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.name != null';
    if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+ '%\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+ '%\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+ '%\'';  
    if (!technology.equals(''))
      soql += ' and interested_technologies__c includes (\''+technology+'\')';

    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> technologies {
    get {
      if (technologies == null) {

        technologies = new List<String>();
        Schema.DescribeFieldResult field = Contact.interested_technologies__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          technologies.add(f.getLabel());

      }
      return technologies;          
    }
    set;
  }

  /*public List<String> options {
    get {
      if (options == null) {

        options = new List<String>();
        Schema.DescribeFieldResult field = Account.Name.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          options.add(f.getLabel());

      }
      return options;          
    }
    set;
  }*/
  
  //builds a picklist of account names based on their account id

  public List<selectOption> getaccts() {

      List<selectOption> options = new List<selectOption>(); 
  //new list for holding all of the picklist options
      options.add(new selectOption('', '- None -')); 
  //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
      for (Account account : [SELECT Id, Name FROM Account]) { 
  //query for Account records 
          options.add(new selectOption(account.Name, account.Name)); 
  //for all records found - add them to the picklist options
      }
      return options; //return the picklist options
  }

}
Here is my visualforce page:
<apex:page controller="ContactSearchController" sidebar="false">

  <apex:form >
  <apex:pageMessages id="errors" />

  <apex:pageBlock title="Search Collaborative Wide Staff Directory" mode="edit">

  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">

      <apex:pageBlock title="Search Properties" mode="edit" id="criteria">

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementById("technology").options[document.getElementById("technology").selectedIndex].value
          );
      }
      </script> 

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="technology" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="firstName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Interested Technologies<br/>
          <select id="technology" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!accts}" var="tech">
              <option value="{!tech}">{!tech}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>

      <!--<apex:pageBlockSection title="Custom Picklist Using selectList and selectOptions">
          <apex:selectList value="{!options}" multiselect="false" size="1">
                  <apex:selectOptions value="{!accts}"/>
          </apex:selectList>
      </apex:pageBlockSection>-->

      </apex:pageBlock>

    </td>
    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!contacts}" var="contact">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.firstName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.lastName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.name}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Technologies" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="interested_technologies__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.interested_technologies__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

    </td>
  </tr>
  </table>

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />           
  </apex:pageBlock>    

  </apex:pageBlock>

  </apex:form>

</apex:page>
What am I missing?   Any help is much appreciated.

 
Hi all,

I have this controller and component which allows for a dynamic search to help candidates select the name of the right college account.  I want to display other criteria for the end-user in the 'results table' so that they can choose the right account, especially if there are duplicate account names that appear in the search results table.  For example, I would like to add the ability of city, state to be displayed when they search for the account name.

Here is the controller: 
public class ProfileSubmitController {

    public List<SelectOption> genders { get; set; }
    public List<SelectOption> ethnicity { get; set; }
    public List<SelectOption> eligibleToWorkUS { get; set; }
    public List<SelectOption> freeOrReducedLunch { get; set; }
    public List<SelectOption> grantPellRecipient { get; set; }
    public List<SelectOption> parentsHighestEducation { get; set; }
    public List<SelectOption> states { get; set; }
    //public List<SelectOption> collegeList { get; set; }
    public List<SelectOption> primaryPhoneTypes { get; set; }
    public List<SelectOption> primaryAddressTypes { get; set; }
    public List<SelectOption> otherPhoneTypes { get; set; }
    public List<SelectOption> otherAddressTypes { get; set; }
    public List<SelectOption> majorCategory { get; set; }
    public List<SelectOption> secondMajorCategory { get; set; }
    public List<SelectOption> minorCategory { get; set; }

    public ProfileSubmitController() {
        
        eligibleToWorkUS = new List<SelectOption>();
        Schema.DescribeFieldResult fieldResult = Application__c.Eligible_to_work_in_US__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            eligibleToWorkUS.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        genders = new List<SelectOption>();
        genders.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.Gender__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            genders.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        ethnicity = new List<SelectOption>();
        ethnicity.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.Ethnicity__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            ethnicity.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        freeOrReducedLunch = new List<SelectOption>();
        fieldResult = Application__c.GAP_Grant_Free_or_Reduced_Lunch__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            freeOrReducedLunch.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        grantPellRecipient = new List<SelectOption>();
        fieldResult = Application__c.Gap_Pell_Grant_Recipient__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            grantPellRecipient.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        parentsHighestEducation = new List<SelectOption>();
        fieldResult = Application__c.Parents_Highest_Level_of_education__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            parentsHighestEducation.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        Map<String, State_List__c> stateList = State_List__c.getAll();
        states = new List<SelectOption>();
        states.add(new SelectOption('', 'Please Select...'));
        List<SelectOption> statesAux = new List<SelectOption>();
        for (String stateName : stateList.keySet()){
            statesAux.add(new SelectOption(stateList.get(stateName).Abbreviation__c, stateName));
        }
        statesAux.sort();
        states.addAll(statesAux);
/*
        collegeList = new List<SelectOption>();
        collegeList.add(new SelectOption('', 'Please Select...'));
        List<Account> sitesList = [SELECT Name FROM Account WHERE RecordType.Name = 'Colleges & Universities'];
        for (Account acc : sitesList){
            if (acc.Name != null){
                collegeList.add(new SelectOption(acc.Id, acc.Name));
            }
        }
*/
        primaryPhoneTypes = new List<SelectOption>();
        primaryPhoneTypes.add(new SelectOption('', 'Please Select...'));
        primaryPhoneTypes.add(new SelectOption('Home', 'Home'));
        primaryPhoneTypes.add(new SelectOption('Cell', 'Cell'));
        primaryPhoneTypes.add(new SelectOption('Office 1', 'Office'));
        primaryPhoneTypes.add(new SelectOption('Other', 'Other'));

        primaryAddressTypes = new List<SelectOption>();
        primaryAddressTypes.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.npe01__Primary_Address_Type__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            primaryAddressTypes.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        otherPhoneTypes = new List<SelectOption>();
        otherPhoneTypes.add(new SelectOption('', 'Please Select...'));
        otherPhoneTypes.add(new SelectOption('Home', 'Home'));
        otherPhoneTypes.add(new SelectOption('Cell', 'Cell'));
        otherPhoneTypes.add(new SelectOption('Office', 'Office'));
        otherPhoneTypes.add(new SelectOption('Other', 'Other'));

        otherAddressTypes = new List<SelectOption>();
        otherAddressTypes.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.Other_Address_Type__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            otherAddressTypes.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        majorCategory = new List<SelectOption>();
        majorCategory.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.College_Major_Category_new__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            majorCategory.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        secondMajorCategory = new List<SelectOption>();
        secondMajorCategory.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.College_Major_Category_2nd_Major__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            secondMajorCategory.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        minorCategory = new List<SelectOption>();
        minorCategory.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.College_Minor_Category__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            minorCategory.add(new SelectOption(f.getLabel(), f.getValue()));
        }

    }

    @RemoteAction
    public static Boolean savePageOne(String application, String myContact){
        List<Breakthrough_Application_Settings__c> settings = [SELECT Name, 
                                                                    Regular_Deadline__c,
                                                                    Backdoor_Application_Open__c
                                                            FROM Breakthrough_Application_Settings__c 
                                                            WHERE Active__c = true LIMIT 1];
        Datetime backdoorOpen = Datetime.newInstance(settings[0].Backdoor_Application_Open__c, Time.newInstance(0,0,0,0));
        Boolean backdoorApplicationOpen = Datetime.now() >= backdoorOpen;   
        
        Contact cont = (Contact)JSON.deserialize(myContact, Contact.Class);
        Application__c app = (Application__c)JSON.deserialize(application, Application__c.Class);

        if (String.isBlank(cont.College__c) && String.isNotBlank(cont.Other_College__c)){
            RecordType collegeRecordType = [SELECT Id FROM RecordType WHERE Name = 'Colleges & Universities'];
            Account newCollege = new Account(RecordTypeId = collegeRecordType.Id, Name = cont.Other_College__c);
            insert newCollege;
            cont.College__c = newCollege.Id;
        }

        cont.Other_College__c = '';

        update cont;
        app.Page_1_Status__c = 'Complete';

        if (backdoorApplicationOpen) {
            RecordType recordType = [select Name from RecordType where Name = 'Backdoor' and SObjectType = 'Application__c'];
            app.RecordTypeId = recordType.Id;
            app.X2nd_City_Preference__c = null;
            app.X2nd_City_Housing_Needed__c = null;
            app.X3rd_City_Preference__c = null;
            app.X3rd_City_Housing_Needed__c = null;
        }
        
        try {
            update app;
        } catch (Exception e) {
            app.Page_1_Status__c = 'In Progress';
            update app;
        }
        Datetime regularDeadline = Datetime.newInstance(settings[0].Regular_Deadline__c, Time.newInstance(0,0,0,0)).addDays(1);
        return ((Datetime.now() >= regularDeadline) && !backdoorApplicationOpen);
        
    }

    @RemoteAction
    public static List<Result> getSearchResults(String searchTerm) {
        List<Result> resultsList = new List<Result>();
        
        searchTerm = searchTerm + '*';
        
        List<List<sObject>> searchResults = [FIND :searchTerm IN ALL FIELDS RETURNING Account(Id, Name WHERE RecordType.Name = 'Colleges & Universities')];

        if(!searchResults.isEmpty()) {
            for(List<sObject> objects : searchResults) {
                for(sObject obj : objects) {
                    Account a = (Account)obj;
                    Result r = new Result(a.Name, a.Id);
                    resultsList.add(r);
                }
            }
        }
        
        return resultsList;
    }
    
    public class Result {
        public String name {get; set;}
        public String recordId {get; set;}       
        public Result(String name, String recordId) {
            this.name = name;
            this.recordId = recordId;
        }
    }

}
Hi All,

I am still learning how to write test class coverage.  Working on an org where a controller never had proper test code coverage.  

Here is the controller:
public class UpdateResumeController {
    
    public List<Organizational_History__c> breakthroughHistoryList {get; set;}
    public List<Organizational_History__c> educationHistoryList {get; set;}
    public List<Organizational_History__c> employmentHistoryList {get; set;}
    public List<SelectOption> sitesOptionList {get; set;}
    public Boolean editBreakthrough {get; set;}
    public Boolean editEducation {get; set;}
    public Boolean editEmployment {get; set;}
    public Boolean allowEdit {get; set;} 
    public String loggedInContactId;
    private Id organizationId;
    private Id breakthroughRecordTypeId;
    private Id educationRecordTypeId;
    private Id employmentRecordTypeId;
    
    public String getLoggedInContactId() {
        return loggedInContactId;
    }
    
    public void setLoggedInContactId(String currentContactId) {
        if (String.isEmpty(loggedInContactId)) {
            loggedInContactId = currentContactId;
            breakthroughHistoryList = [SELECT Organization__c, Type__c, Breakthrough_Year__c FROM Organizational_History__c WHERE Breakthrough_Contact__c = :loggedInContactId AND RecordType.Name = 'Breakthrough History' ORDER BY Breakthrough_Year__c ASC];
            educationHistoryList = [SELECT School__c, Graduation_Year__c, Field_of_Study__c, Degree__c, City__c, State__c, Country__c FROM Organizational_History__c WHERE Education_Contact__c = :loggedInContactId AND RecordType.Name = 'Educational History' ORDER BY Graduation_Year__c ASC];
            employmentHistoryList = [SELECT Employer__c, Role__c, City__c, State__c, Country__c, Start_Year__c, End_Year__c FROM Organizational_History__c WHERE Employment_Contact__c = :loggedInContactId AND RecordType.Name = 'Employment History' ORDER BY Start_Year__c ASC];
            organizationId = [SELECT AccountId FROM Contact WHERE Id = :loggedInContactId].AccountId;
            breakthroughRecordTypeId = [SELECT Id FROM RecordType WHERE Name = 'Breakthrough History'].Id;
            educationRecordTypeId = [SELECT Id FROM RecordType WHERE Name = 'Educational History'].Id;
            employmentRecordTypeId = [SELECT Id FROM RecordType WHERE Name = 'Employment History'].Id;
        }
    }
    
    public UpdateResumeController(){
        sitesOptionList = new List<SelectOption>();
        List <Account> sitesList = [SELECT Portal_Display_Name__c FROM Account WHERE RecordType.Name = 'Breakthrough Organization' AND Program_Status__c IN ('Active', 'Inactive')];
        for (Account acc : sitesList){
            if (acc.Portal_Display_Name__c != null){
                sitesOptionList.add(new SelectOption(acc.Id, acc.Portal_Display_Name__c));
            }
        }
        editBreakthrough = false;
        editEducation = false;
        editEmployment = false;
        String contactId = ApexPages.currentPage().getParameters().get('Id');
        system.debug(contactId);
        system.debug(loggedInContactId);
        allowEdit = loggedInContactId == contactId || contactId == null;
    }
    
    public void enableEditBreakthrough(){
        editBreakthrough = true;
    }
    public void cancelEditBreakthrough(){
        breakthroughHistoryList = [SELECT Organization__c, Type__c, Breakthrough_Year__c FROM Organizational_History__c WHERE Breakthrough_Contact__c = :loggedInContactId AND RecordType.Name = 'Breakthrough History' ORDER BY Breakthrough_Year__c ASC];
        editBreakthrough = false;
    }
    public void addBreakthroughHistory(){
        List<Organizational_History__c> breakthroughHistoryListAux = new List<Organizational_History__c>();
        breakthroughHistoryListAux.add(new Organizational_History__c(Breakthrough_Contact__c=loggedInContactId, RecordTypeId = breakthroughRecordTypeId));
        breakthroughHistoryListAux.addAll(breakthroughHistoryList);
        breakthroughHistoryList = breakthroughHistoryListAux;
        enableEditBreakthrough();
    }
    public void saveBreakthroughHistory(){
        upsert breakthroughHistoryList;
        editBreakthrough = false;
    }
    
    public void enableEditEducation(){
        editEducation = true;
    }
    public void cancelEditEducation(){
        educationHistoryList = [SELECT School__c, Graduation_Year__c, Field_of_Study__c, Degree__c, City__c, State__c, Country__c FROM Organizational_History__c WHERE Education_Contact__c = :loggedInContactId AND RecordType.Name = 'Educational History' ORDER BY Graduation_Year__c ASC];
        editEducation = false;
    }
    public void addEducationHistory(){
        List<Organizational_History__c> educationHistoryListAux = new List<Organizational_History__c>();
        educationHistoryListAux.add(new Organizational_History__c(Organization__c = organizationId, Education_Contact__c=loggedInContactId, RecordTypeId = educationRecordTypeId));
        educationHistoryListAux.addAll(educationHistoryList);
        educationHistoryList = educationHistoryListAux;
        enableEditEducation();
    }
    public void saveEducationHistory(){
        upsert educationHistoryList;
        editEducation = false;
    }
    
    public void enableEditEmployment(){
        editEmployment = true;
    }
    public void cancelEditEmployment(){
        employmentHistoryList = [SELECT Employer__c, Role__c, City__c, Country__c, State__c, Start_Year__c, End_Year__c FROM Organizational_History__c WHERE Employment_Contact__c = :loggedInContactId AND RecordType.Name = 'Employment History' ORDER BY Start_Year__c ASC];
        editEmployment = false;
    }
    public void addEmploymentHistory(){
        List<Organizational_History__c> employmentHistoryListAux = new List<Organizational_History__c>();
        employmentHistoryListAux.add(new Organizational_History__c(Organization__c = organizationId, Employment_Contact__c=loggedInContactId, RecordTypeId = employmentRecordTypeId));
        employmentHistoryListAux.addAll(employmentHistoryList);
        employmentHistoryList = employmentHistoryListAux;
        enableEditEmployment();
    }
    public void saveEmploymentHistory(){
        upsert employmentHistoryList;
        editEmployment = false;
    }
    
    public PageReference deleteRecord(){
        String recordId = Apexpages.currentPage().getParameters().get('recordId');
        String recordType = Apexpages.currentPage().getParameters().get('recordType');
        system.debug(recordType);
        system.debug(recordId);
        delete [SELECT Id FROM Organizational_History__c WHERE Id = :recordId];
        Integer i = 0;
        if (recordType == 'breakthrough'){
            breakthroughHistoryList = [SELECT Organization__c, Type__c, Breakthrough_Year__c FROM Organizational_History__c WHERE Breakthrough_Contact__c = :loggedInContactId AND RecordType.Name = 'Breakthrough History' ORDER BY Breakthrough_Year__c ASC];
        } else if (recordType == 'education'){
            educationHistoryList = [SELECT School__c, Graduation_Year__c, Field_of_Study__c, Degree__c, City__c, State__c FROM Organizational_History__c WHERE Education_Contact__c = :loggedInContactId AND RecordType.Name = 'Educational History' ORDER BY Graduation_Year__c ASC];
        } else if (recordType == 'employment'){
            employmentHistoryList = [SELECT Employer__c, Role__c, City__c, State__c, Country__c, Start_Year__c, End_Year__c FROM Organizational_History__c WHERE Employment_Contact__c = :loggedInContactId AND RecordType.Name = 'Employment History' ORDER BY Start_Year__c ASC];
        }
        return null;
    }
}
Here is the test class (not sufficient only at 20%):
@isTest
private class UpdateResumeControllerTest {

  static testMethod void myUnitTest() {
    
    //RecordType bo = [SELECT Id FROM RecordType WHERE Name = 'Breakthrough Organization'];
    //RecordType alumni = [SELECT Id FROM RecordType WHERE Name = 'Student Alumni'];

    Account testAcc = AccountUtils.createBreakthroughOrgAccount('Breakthrough Alumni Test', true);
    testAcc.Program_Status__c='Inactive';
    update testAcc;
    //insert testAcc;
    
    Contact testContact = ContactUtils.createAlumniContact('MyNew', 'Alumnus1', 'myalumnus1@org.test', testAcc.Id, true);
    //insert testContact;
    
    //Profile testProf = [SELECT Id FROM Profile WHERE Name='Portal Per Login User'];
    
    User testUser = UserUtils.createAlumniCommunityUser(testContact, false, true);
    //insert testUser;  
    Test.startTest();
    system.runAs(testUser){
      
      UpdateResumeController urc = new UpdateResumeController();
    
      
        urc.enableEditBreakthrough();
      
      
      system.assert(urc.editBreakthrough);        
    }
    Test.stopTest();
  }
}

 
Hi all,

I am still learning on writing my test code coverage.  I would like to get as close to 100% as possible with the below test class.  Any suggestions on what I could add to get the test code coverage higher?  It's currently at 77%.

Thanks in advance for your feedback.

Controller:
global class CustomLoginController {

    /*Initialization*/
    
    global CustomLoginController () {

    List<Breakthrough_Application_Settings__c> settings = [select Display__c,
                Application_Open__c,
                Regular_Deadline__c,
                Backdoor_Application_Open__c,
                Name 
              from Breakthrough_Application_Settings__c 
              where Active__c = true LIMIT 1];
        if (settings.size() > 0) {
        Datetime regAppOpen = Datetime.newInstance(settings[0].Application_Open__c, Time.newInstance(0,0,0,0));
        Datetime backdoorOpen = Datetime.newInstance(settings[0].Backdoor_Application_Open__c, Time.newInstance(0,0,0,0));
        Datetime regularDeadline = Datetime.newInstance(settings[0].Regular_Deadline__c, Time.newInstance(0,0,0,0)).addDays(1);
        this.regularApplicationOpen = Datetime.now() >= regAppOpen;
        this.backdoorApplicationOpen = Datetime.now() >= backdoorOpen;
        this.isRegularDeadlineReach = Datetime.now() >= regularDeadline;
        this.isDisplayed = settings[0].Display__c;
        }
    }
    
    /*End Initialization*/
    
    /*Properties*/
    
    global String username{get;set;}
    global String password{get;set;}
    
    global String firstName {get; set;}
    global String lastName {get; set;}
    global String email {get; set;}
    global String createPassword {get; set {password = value == null ? value : value.trim(); } }
    global String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
    global String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }

    public Breakthrough_Application_Settings__c settings { get; set; }
    public Boolean isDisplayed { get; set; }
    public Boolean backdoorApplicationOpen { get; set; }
    public Boolean regularApplicationOpen { get; set; }
    public Boolean isRegularDeadlineReach { get; set; }

    /*End Properties*/
    
    /*Action Methods*/
    
    global PageReference forwardToCustomAuthPage() {
        return new PageReference( '/CustomLogin');
    }
    
    global PageReference login() {
    
    
        return Site.login(username, password, null);
    }
    
    private boolean isValidPassword() {
        return password == confirmPassword;
    }
    
    @TestVisible
    private Id accountId;
    private String emailAddress;
    
    global PageReference registerUser() {
        Breakthrough_Application_Login_Settings__c settings = Breakthrough_Application_Login_Settings__c.getOrgDefaults();
        // it's okay if password is null - we'll send the user a random password in that case
        if (!isValidPassword()) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
            ApexPages.addMessage(msg);
            return null;
        }
        
        //String profileId = UserUtils.getAlumniCommunityProfileId();
        String profileId = settings.ProfileId__c;      
        String roleEnum = null; // To be filled in by customer.
        
        String userName = email;
        
        // Get the email address from the Custom Setting
        emailAddress = BCUtils.getDefaultAlumniDirectoryEmail();
        
        String baseURL = BCUtils.getDefaultAlumniDirectoryBaseURL();
        
        Boolean sendEmail = false;
        String subject = '';
        String htmlBody = '';
        
        // Create a savepoint while AccountNumber is null
        Savepoint sp = null;
        Contact contact;
        // BC-20 match portal user to existing SFDC contact that belongs in a portal enabled account
        List<Contact> contacts = [select Id, AccountId from Contact where Email = :email and Account.IsPartner = true];
        if (contacts.size() == 0) {
            
            // Case 1, 2c, 3c
            
            // no existing contact: let SFDC create a new contact under the default Alumni Community account
           // accountId = AccountUtils.getAlumniCommunityAccountId();
            accountId = settings.AccountId__c;
            // Create a savepoint before the contact is created
            sp = Database.setSavepoint();
            
            // Create the contact with the Default account Id
            //Contact c = ContactUtils.createContact(firstName, lastName, email, accountId, RecordTypes.contactAlumniTypeId, true);
            contact = new Contact(
              FirstName = firstName,
              LastName = lastName,
              Email = email,
              AccountId = accountId,
              RecordTypeId = RecordTypes.contactAlumniTypeId,
              OwnerId = settings.OwnerId__c
          );
          insert contact;
            
            
            
            // Send email address to Breakthrough staff letting them know that a new Portal User has been created.
            if(emailAddress != null)
            {
                sendEmail = true;
                subject = 'New portal user lacking valid existing contact';
                htmlBody = 'A new user has registered for the portal without having an existing contact or having a contact that is not associated with a portal enabled account.<br/><br/><a href="' + baseUrl + '/' + contact.Id + '">' + firstName + ' ' + lastName + '</a>';
            }
           
        } else if (contacts.size() >= 1) {
            
            List<User> userList = [Select Id from user where ContactId IN :contacts and ProfileId = :profileId and (UserType = 'PowerPartner' or UserType = 'Partner')];
            
            if(!userList.isEmpty())
            {
                // Case 2a, 3a
                
                // a user already exists for this contact: display an error
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,
                'You already have a Portal account. Please contact Breakthrough Collaborative if this is in error.');
                ApexPages.addMessage(msg);
                return null;
            }
            
            // Case 2b, 3b - match one unique existing contact: let SFDC use this contact
            accountId = contacts[0].AccountId;
            contact = contacts[0];
            if(contacts.size() > 1 && emailAddress != null)
            {
                // Send email address to Breakthrough staff letting them know that a new Portal User has been created.
                sendEmail = true;
                
                subject = 'New portal user has multiple matching contacts';
                htmlBody = 'A new user has registered for the portal while having multiple contacts; they have been matched to one.<a href="' + baseUrl + '/' + contacts[0].Id + '">' + firstName + ' ' + lastName + '</a>';
                
            }
        }
        
        //Role role = [Select Id from Role where Id = '00Ee0000000NP3SEAW'];
        
        User u = new User();
        u.Username = userName;
        u.Email = email;
        u.FirstName = firstName;
        u.LastName = lastName;
        //u.CommunityNickname = communityNickname;
        u.communityNickname = generateNickname(firstName, lastName);
        u.ProfileId = profileId;
        //u.ReceivesInfoEmails = true;
        u.UserPermissionsSFContentUser = true;
        u.ContactId = contact.Id;
        
        String userId = null;
        
        try{
            userId = Site.createPortalUser(u, accountId, password);
        }
        catch(Exception e)
        {
            // Rollback to before the contact was created
            if(sp != null)
                Database.rollback(sp);
            
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,
                e.getMessage());
            ApexPages.addMessage(msg);
            return null;
        }
        
        if (userId != null) {
            
            if(sendEmail)
                CommonUtils.sendEmail(new String[]{emailAddress}, emailAddress, 'Alumni Directory', subject, htmlBody);
            
            if (password != null && password.length() > 1) {
                return Site.login(userName, password, ApexPages.currentPage().getParameters().get('startURL'));
            }
            else {
                PageReference page = System.Page.CommunitiesSelfRegConfirm;
                page.setRedirect(true);
                return page;
            }
        }
        else
        {
            // Rollback to before the contact was created
            if(sp != null)
                Database.rollback(sp);
        }
        
        return null;
    }
    
    /*End Action Methods*/
    
    /*Helper Methods*/
    
    private String generateNickname(String firstName, String lastName)
    {
        String communityNickname = '';
        
        if(firstName != null && firstName != '')
            communityNickname += firstName.substring(0, 1);
        
        communityNickname += lastName + CommonUtils.getCurrentTimeMillis();
        
        return communityNickname;
    }
    
    /*End Helper Methods*/
}

Test Code Class:
@isTest
public class CustomLoginControllerTest {
    @IsTest(SeeAllData=true)
    public static void testCommunitiesSelfRegController() {
        
        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;

        Test.startTest();

        CustomLoginController controller = new CustomLoginController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@force.com';
        controller.communityNickname = 'test';
        
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null);
        
        controller.createPassword = 'abcd1234';
        controller.confirmPassword = 'abcd123';
        System.assert(controller.registerUser() == null);

        System.assertEquals(true, controller.backdoorApplicationOpen);
        System.assertEquals(true, controller.regularApplicationOpen);
        System.assertEquals(true, controller.isRegularDeadlineReach);
        System.assertEquals(false, controller.isDisplayed);

        Test.stopTest();
    }
    
    @isTest
    public static void userWithNoMatchingContactCreatedUnderDefaultAccount() {

        BCUtils.createAlumniDirectorySettings('Default Portal Account', 'resumeUrl', true);

        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;
        
        Account a1 = AccountUtils.createBreakthroughOrgAccount('Default Portal Account', false);
        Account a2 = AccountUtils.createBreakthroughOrgAccount('Another Portal Account', false);
        List<Account> accounts = new List<Account> { a1, a2 };
        insert accounts;
        a1.isPartner = true;
        a2.isPartner = true;
        update accounts;
        Breakthrough_Application_Login_Settings__c settings = new Breakthrough_Application_Login_Settings__c();
        settings.OwnerId__c = UserInfo.getUserId();
        settings.AccountId__c = a1.Id;
        insert settings;
        Test.startTest();
        
        CustomLoginController controller = new CustomLoginController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@alumni.test';
        controller.communityNickname = 'test';
        
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null);
        
        System.assertEquals(a1.Id, controller.accountId);
        System.assertEquals(false, ApexPages.hasMessages());
        
        System.assertEquals(false, controller.backdoorApplicationOpen);
        System.assertEquals(true, controller.regularApplicationOpen);
        System.assertEquals(false, controller.isRegularDeadlineReach);
        System.assertEquals(true, controller.isDisplayed);
        
        Test.stopTest();
    }
    
    @isTest
    public static void userWithOneMatchingContactCreatedUnderMatchedAccount() {
        BCUtils.createAlumniDirectorySettings('Default Portal Account', 'resumeUrl', true);

        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;
        
        Account a1 = AccountUtils.createBreakthroughOrgAccount('Default Portal Account', false);
        Account a2 = AccountUtils.createBreakthroughOrgAccount('Another Portal Account', false);
        List<Account> accounts = new List<Account> { a1, a2 };
        insert accounts;
        a1.isPartner = true;
        a2.isPartner = true;
        update accounts;
        
        Contact c = ContactUtils.createAlumniContact('Test', 'Alumni', 'test@alumni.test', a2.Id, true);
        
        Test.startTest();
        
        CustomLoginController controller = new CustomLoginController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@alumni.test';
        controller.communityNickname = 'test';
        
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null);
        
        System.assertEquals(a2.Id, controller.accountId);
        System.assertEquals(false, ApexPages.hasMessages());

        System.assertEquals(false, controller.backdoorApplicationOpen);
        System.assertEquals(true, controller.regularApplicationOpen);
        System.assertEquals(false, controller.isRegularDeadlineReach);
        System.assertEquals(true, controller.isDisplayed);
        
        Test.stopTest();
    }
    
    @isTest
    public static void userWithMultipleMatchingContactCreated() {
        BCUtils.createAlumniDirectorySettings('Default Portal Account', 'resumeUrl', true);

        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;
        
        Account a1 = AccountUtils.createBreakthroughOrgAccount('Default Portal Account', false);
        Account a2 = AccountUtils.createBreakthroughOrgAccount('Another Portal Account', false);
        List<Account> accounts = new List<Account> { a1, a2 };
        insert accounts;
        a1.isPartner = true;
        a2.isPartner = true;
        update accounts;
        
        Contact c1 = ContactUtils.createAlumniContact('Test', 'Alumni', 'test@alumni.test', a1.Id, true);
        Contact c2 = ContactUtils.createAlumniContact('Test', 'Alumni', 'test@alumni.test', a2.Id, true);
        
        Test.startTest();
        
        CustomLoginController controller = new CustomLoginController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@alumni.test';
        controller.communityNickname = 'test';
        
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null);
        
        System.assertNotEquals(null, controller.accountId);
        System.assertEquals(false, ApexPages.hasMessages());
        
        System.assertEquals(false, controller.backdoorApplicationOpen);
        System.assertEquals(true, controller.regularApplicationOpen);
        System.assertEquals(false, controller.isRegularDeadlineReach);
        System.assertEquals(true, controller.isDisplayed);

        Test.stopTest();
    }

    @isTest
    public static void CustomAuthPage() {
        BCUtils.createAlumniDirectorySettings('Default Portal Account', 'resumeUrl', true);

        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;

        PageReference ref = new PageReference('/apex/CustomLogin');
        Test.setCurrentPage(ref);
        CustomLoginController controller = new CustomLoginController();

        Test.startTest();
            ref = controller.forwardToCustomAuthPage();
        Test.stopTest();
        system.assertEquals('/CustomLogin', ref.getUrl());
    }
}

 
Hi all,

I am struggling with figuring out why my last test keeps failing.  Wondering if a second pair of eyes can pinpoint why the 'Application' is not being created in the test class.

Here is my test class (only showing the last test due to size restrictions):
static testMethod void newApplicationTest() {
        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Application_Closed__c = Date.valueOf(Datetime.now().addDays(20));
        setting.Backdoor_Application_Open__c = Date.today();
        setting.Active__c = true;
        insert setting;
        Account a = AccountUtils.createBreakthroughOrgAccount('Breakthrough Alumni Test', true);
        Contact c = ContactUtils.createAlumniContact('MyNew', 'Alumnus1', 'myalumnus1@org.test', a.Id, true);
        
        User u = UserUtils.createAlumniCommunityUser(c, false, true);
        
        PageReference ref = new PageReference('/apex/ApplicationStatus');
        Test.setCurrentPage(ref);
        ApplicationStatusController controller = new ApplicationStatusController();
        Test.startTest();
            System.runAs(u) {
                ref = controller.newApplication();
            }
        Test.stopTest();
        system.assert(controller.application.Id != null);
    }
Here is my controller:
public class ApplicationStatusController {
  
  public List<ReviewStatus> reviewStatusList { get; set; }
  public Application__c application { get; set; }
  public Recommendation_N__c recommendation { get; set; }
  public Breakthrough_Application_Settings__c settings { get; set; }
  public User user { get; set; }
  public Boolean applicationClosed { get; set; }
  public String recommendationDate { get; set; }
  public String whenSubmitted { get; set; }
  private Map<String,String> citiesMap {get;set;}
  public Boolean backdoorApplicationOpen { get; set; }
  public Boolean isRegularDeadlineReach { get; set; }
  public Boolean isDisplayed { get; set; }
  
  public ApplicationStatusController() {
    this.settings = [select Regular_Deadline__c,
                  Early_Action_Deadline__c, 
                Early_Action_Rollover__c, 
                First_Rollover__c, 
                Second_Rollover__c, 
                Third_Rollover__c,
                Application_Closed__c,
                Backdoor_Application_Open__c,
                Backdoor_Application_Closed__c,
                Display__c,
                Name 
              from Breakthrough_Application_Settings__c 
              where Active__c = true LIMIT 1];
    Datetime regularDeadline = Datetime.newInstance(this.settings.Regular_Deadline__c, Time.newInstance(0,0,0,0)).addDays(1);
    this.applicationClosed = settings.Application_Closed__c <= Date.today();
    this.isDisplayed = settings.Display__c;
    this.isRegularDeadlineReach = Datetime.now() >= regularDeadline;
    Datetime backdoorOpen = Datetime.newInstance(this.settings.Backdoor_Application_Open__c, Time.newInstance(0,0,0,0));
    this.backdoorApplicationOpen = Datetime.now() >= backdoorOpen;
    this.loadApplication();
  }

  private void loadApplication() {
    this.user = [select ContactId from User where Id =: UserInfo.getUserId()];
    
    List<Application__c> applicationList = [select Application_Year__c, 
                            AppStatus__c, 
                            Contact__c,
                            Page_1_Status__c,
                            Page_2_Status__c,
                            Page_3_Status__c,
                            Page_4_Status__c,
                            Page_5_Status__c,
                            X1st_City_Preference__c,
                            X1st_City_Preference__r.Name,
                            X1st_City_Preference__r.Early_Decision_Participant__c,
                            X2nd_City_Preference__c,
                            X2nd_City_Preference__r.Name,
                            X2nd_City_Preference__r.Early_Decision_Participant__c,
                            X3rd_City_Preference__c,
                            X3rd_City_Preference__r.Name,
                            X3rd_City_Preference__r.Early_Decision_Participant__c,
                            Mock_Teaching_Video_Link__c,
                            Ask_for_Mock_Teaching_Video__c,
                            WhenSubmitted__c,
                            Frozen__c,
                            Early_Rollover_Done__c,
                            First_Rollover_Done__c,
                            Second_Rollover_Done__c,
                            Third_Rollover_Done__c,
                            OwnerId,
                            RecordType.Name
                            from Application__c 
                            where Application_Year__c =: this.settings.Name
                            and Contact__c =: user.ContactId 
                            and RecordType.Name IN ('Backdoor', 'Portal Application')
                            LIMIT 1];
    if (!applicationList.isEmpty()) {
      this.application = applicationList[0];
      this.whenSubmitted = this.application.WhenSubmitted__c == null ? '' : this.application.WhenSubmitted__c.format('EEEE, MMMM d, yyyy \'at\' h:mma');
      this.loadRecommendation();
      this.loadCitiesMap();
      this.loadReviewStatus();
    }
  }
  
  private void loadReviewStatus() {
    Datetime earlyDeadline = Datetime.newInstance(this.settings.Early_Action_Deadline__c, Time.newInstance(0,0,0,0)).addDays(1);
    
    Map<String, String> appStatusToReviewStatusMap = this.loadStatusMap();
    
    this.reviewStatusList = new List<ReviewStatus>();
    if (this.application.RecordType.Name == 'Backdoor') {
      this.loadReviewStatusForBackdoor(appStatusToReviewStatusMap);
    } else {
      if (!String.isEmpty(this.application.X1st_City_Preference__c)) {
        ReviewStatus review = new ReviewStatus();
        review.preference = this.application.X1st_City_Preference__r.Name;
        if (this.application.X1st_City_Preference__r.Early_Decision_Participant__c == 'Yes' && this.application.WhenSubmitted__c <= earlyDeadline) {
          review.reviewDeadline = this.settings.Early_Action_Rollover__c.month() + '/' + (this.settings.Early_Action_Rollover__c.day()+1) + '/' + this.settings.Early_Action_Rollover__c.year();
        } else {
          review.reviewDeadline = this.settings.First_Rollover__c.month() + '/' + (this.settings.First_Rollover__c.day()+1) + '/' + this.settings.First_Rollover__c.year();
        }
        if (this.application.AppStatus__c == 'Wait Listed' || this.application.AppStatus__c == 'Waitlisted/No Offer Extended' || this.application.AppStatus__c == 'No Offer Extended') {
          review.status = 'No Offer Extended';
        } else {
          if (this.application.Early_Rollover_Done__c && this.application.X1st_City_Preference__r.Early_Decision_Participant__c == 'Yes' && this.application.WhenSubmitted__c <= earlyDeadline) {
            review.status = 'No Offer Extended';
          } else if (this.application.First_Rollover_Done__c) {
            review.status = 'No Offer Extended';
          } else {
            if (this.currentCityIndex()==0) {
              
              review.status = appStatusToReviewStatusMap.containsKey(this.application.AppStatus__c) ? appStatusToReviewStatusMap.get(this.application.AppStatus__c) : '';
                
            } else if(this.currentCityIndex()>0){
              
              if (this.application.AppStatus__c == 'Hold / Keep' || this.application.AppStatus__c == 'Assigned') 
                review.status = 'No Offer Extended';
              if (this.application.AppStatus__c == 'Offer Pending' || this.application.AppStatus__c == 'Offer Accepted' || this.application.AppStatus__c == 'Offer Rejected' || this.application.AppStatus__c == 'Rejected' || this.application.AppStatus__c == 'Applicant Dismissed' || this.application.AppStatus__c == 'Applicant Has Withdrawn' || this.application.AppStatus__c == 'Teaching Fellow Dismissed' || this.application.AppStatus__c == 'Teaching Fellow Withdrawn')
                review.status = 'No Offer Extended';
                
            }
          }
          
        }
        
        reviewStatusList.add(review);
      }
      if (!String.isEmpty(this.application.X2nd_City_Preference__c)) {
        ReviewStatus review = new ReviewStatus();
        review.preference = this.application.X2nd_City_Preference__r.Name;
        if (this.application.X1st_City_Preference__r.Early_Decision_Participant__c == 'Yes' && this.application.WhenSubmitted__c <= earlyDeadline) {
          review.reviewDeadline = this.settings.First_Rollover__c.month() + '/' + (this.settings.First_Rollover__c.day()+1) + '/' + this.settings.First_Rollover__c.year();
        } else {
          review.reviewDeadline = this.settings.Second_Rollover__c.month() + '/' + (this.settings.Second_Rollover__c.day()+1) + '/' + this.settings.Second_Rollover__c.year();
        }
        if (this.application.AppStatus__c == 'Wait Listed' || this.application.AppStatus__c == 'Waitlisted/No Offer Extended' || this.application.AppStatus__c == 'No Offer Extended') {
          review.status = 'No Offer Extended';
        } else {
          if (this.application.Second_Rollover_Done__c) {
            review.status = 'No Offer Extended';
          } else {
            if (this.currentCityIndex()==1) {
  
              review.status = appStatusToReviewStatusMap.containsKey(this.application.AppStatus__c) ? appStatusToReviewStatusMap.get(this.application.AppStatus__c) : '';
                
            } else if (this.currentCityIndex()>1){
              
              if (this.application.AppStatus__c == 'Hold / Keep' || this.application.AppStatus__c == 'Assigned') 
                review.status = 'No Offer Extended';
              if (this.application.AppStatus__c == 'Offer Pending' || this.application.AppStatus__c == 'Offer Accepted' || this.application.AppStatus__c == 'Offer Rejected' || this.application.AppStatus__c == 'Rejected' || this.application.AppStatus__c == 'Applicant Dismissed' || this.application.AppStatus__c == 'Applicant Has Withdrawn' || this.application.AppStatus__c == 'Teaching Fellow Dismissed' || this.application.AppStatus__c == 'Teaching Fellow Withdrawn')
                review.status = 'No Offer Extended';
                
            } else {
              
              if (this.application.AppStatus__c == 'Hold / Keep' || this.application.AppStatus__c == 'Assigned') 
                review.status = 'Awaiting Review';
              if (this.application.AppStatus__c == 'Offer Pending' || this.application.AppStatus__c == 'Offer Accepted' || this.application.AppStatus__c == 'Offer Rejected' || this.application.AppStatus__c == 'Rejected' || this.application.AppStatus__c == 'Applicant Dismissed' || this.application.AppStatus__c == 'Applicant Has Withdrawn' || this.application.AppStatus__c == 'Teaching Fellow Dismissed' || this.application.AppStatus__c == 'Teaching Fellow Withdrawn')
                review.status = '';
                
            }
          }
        }
        reviewStatusList.add(review);
      }
      if (!String.isEmpty(this.application.X3rd_City_Preference__c)) {
        ReviewStatus review = new ReviewStatus();
        review.preference = this.application.X3rd_City_Preference__r.Name;
        if (this.application.X1st_City_Preference__r.Early_Decision_Participant__c == 'Yes' && this.application.WhenSubmitted__c <= earlyDeadline) {
          review.reviewDeadline = this.settings.Second_Rollover__c.month() + '/' + (this.settings.Second_Rollover__c.day()+1) + '/' + this.settings.Second_Rollover__c.year();
        } else {
          review.reviewDeadline = this.settings.Third_Rollover__c.month() + '/' + (this.settings.Third_Rollover__c.day()+1) + '/' + this.settings.Third_Rollover__c.year();
        }
        if (this.application.AppStatus__c == 'Wait Listed' || this.application.AppStatus__c == 'Waitlisted/No Offer Extended'  || this.application.AppStatus__c == 'No Offer Extended') {
          review.status = 'No Offer Extended';
        } else {
          if (this.application.Third_Rollover_Done__c) {
            review.status = 'No Offer Extended';
          } else {
            if (this.currentCityIndex()==2) {
  
              review.status = appStatusToReviewStatusMap.containsKey(this.application.AppStatus__c) ? appStatusToReviewStatusMap.get(this.application.AppStatus__c) : '';
                
            }else if (this.currentCityIndex()>2) {  
              if (this.application.AppStatus__c == 'Hold / Keep' || this.application.AppStatus__c == 'Assigned') 
                review.status = 'No Offer Extended';
              if (this.application.AppStatus__c == 'Offer Pending' || this.application.AppStatus__c == 'Offer Accepted' || this.application.AppStatus__c == 'Offer Rejected' || this.application.AppStatus__c == 'Rejected' || this.application.AppStatus__c == 'Applicant Dismissed' || this.application.AppStatus__c == 'Applicant Has Withdrawn' || this.application.AppStatus__c == 'Teaching Fellow Dismissed' || this.application.AppStatus__c == 'Teaching Fellow Withdrawn')
                review.status = 'No Offer Extended';
                
            } else {
              
              if (this.application.AppStatus__c == 'Hold / Keep' || this.application.AppStatus__c == 'Assigned') 
                review.status = 'Awaiting Review';
              if (this.application.AppStatus__c == 'Offer Pending' || this.application.AppStatus__c == 'Offer Accepted' || this.application.AppStatus__c == 'Offer Rejected' || this.application.AppStatus__c == 'Rejected' || this.application.AppStatus__c == 'Applicant Dismissed' || this.application.AppStatus__c == 'Applicant Has Withdrawn' || this.application.AppStatus__c == 'Teaching Fellow Dismissed' || this.application.AppStatus__c == 'Teaching Fellow Withdrawn')
                review.status = '';
                
            }
          }
        }
        reviewStatusList.add(review);
      }
      if (this.application.AppStatus__c == 'Wait Listed' || this.application.AppStatus__c == 'Waitlisted/No Offer Extended') {
        ReviewStatus review = new ReviewStatus();
        review.preference = 'National Waitlist';
        review.reviewDeadline = this.settings.Application_Closed__c.month() + '/' + (this.settings.Application_Closed__c.day()+1) + '/' + this.settings.Application_Closed__c.year();
        review.status = '';
        reviewStatusList.add(review);
      }
    }
  }
  
  private void loadReviewStatusForBackdoor(Map<String, String> appStatusToReviewStatusMap) {
    ReviewStatus review = new ReviewStatus();
    if (this.application.AppStatus__c == 'Wait Listed' || this.application.AppStatus__c == 'Waitlisted/No Offer Extended') {
      review.preference = 'National Waitlist';
      review.status = '';
    } else if (this.currentCityIndex() == 0) {
      review.preference = this.application.X1st_City_Preference__r.Name;
      review.status = appStatusToReviewStatusMap.containsKey(this.application.AppStatus__c) ? appStatusToReviewStatusMap.get(this.application.AppStatus__c) : '';
    } else {
      review.preference = 'Rejected Queue';
      review.status = '';
    }
    review.reviewDeadline = this.settings.Backdoor_Application_Closed__c.month() + '/' + (this.settings.Backdoor_Application_Closed__c.day()+1) + '/' + this.settings.Backdoor_Application_Closed__c.year();
    this.reviewStatusList.add(review);
  }

  private void loadCitiesMap(){
    List<String> cities = new List<String>();

    cities.add(this.application.X1st_City_Preference__r.Name);
    cities.add(this.application.X2nd_City_Preference__r.Name);
    cities.add(this.application.X3rd_City_Preference__r.Name);

    List<Breakthrough_Application_City_Queue_Map__c> citiesMapList = [Select Name, City__c, QueueId__c FROM Breakthrough_Application_City_Queue_Map__c Where City__c IN :cities];

    this.citiesMap = new Map<String,String>();

    for(Breakthrough_Application_City_Queue_Map__c c : citiesMapList){
      this.citiesMap.put(c.QueueId__c , c.City__c );
    }
  }

  private Integer currentCityIndex(){
    String currentCity = this.citiesMap.get(String.valueOf(this.application.OwnerId).substring(0, 15));

    if(currentCity == this.application.X1st_City_Preference__r.Name){
      return 0;
    }
    if(currentCity == this.application.X2nd_City_Preference__r.Name){
      return 1;
    }
    if(currentCity == this.application.X3rd_City_Preference__r.Name){
      return 2;
    }
    return -1;
  }
  
  private void loadRecommendation() {
    List<Recommendation_N__c> recommendationList = [select Status__c,
                                Recommender__r.Name,
                                Recommender__r.Email,
                                Orig_Email_Sent_On__c
                            from Recommendation_N__c 
                            where Application__c =: this.application.Id
                            LIMIT 1];
    if (!recommendationList.isEmpty()) {
      this.recommendation = recommendationList[0];
      this.recommendationDate = this.recommendation.Orig_Email_Sent_On__c == null ? '' : this.recommendation.Orig_Email_Sent_On__c.format('EEEE, MMMM d, yyyy \'at\' h:mma');
    }                            
  }
  
  public PageReference submitVideo() {
    return new PageReference('/apex/TeachingVideoSubmissionPage');
  }
  
  public PageReference newApplication() {
    RecordType record = this.backdoorApplicationOpen ? [SELECT Id FROM RecordType WHERE Name = 'Backdoor'] : [SELECT Id FROM RecordType WHERE Name = 'Portal Application'];
    this.application = new Application__c();
    this.application.Application_Year__c = this.settings.Name;
    this.application.Contact__c = this.user.ContactId;
    this.application.AppStatus__c = 'Application In Progress';
    this.application.RecordTypeId = record.Id;
    this.application.When_Started__c = Datetime.now();
    try {
      insert this.application;  
    } catch(Exception e) {
      PageReference ref = new PageReference('/apex/ApplicationStatus');
      ref.setRedirect(true);
      return ref;
    }
    return null;
  }
  
  private Map<String, String> loadStatusMap() {
    Map<String, String> statusMap = new Map<String, String>();
    statusMap.put('Hold / Keep', 'Under Review');
    statusMap.put('Assigned', 'Under Review');
    statusMap.put('Offer Pending', 'Offer Pending');
    statusMap.put('Offer Accepted', 'Offer Accepted');
    statusMap.put('Offer Rejected', 'Offer Rejected');
    statusMap.put('Rejected', 'Offer Rejected');
    statusMap.put('Applicant Dismissed', 'No Offer Extended');
    statusMap.put('Applicant Has Withdrawn', 'Application Withdrawn');
    statusMap.put('Teaching Fellow Dismissed', 'Teaching Fellow Dismissed');
    statusMap.put('Teaching Fellow Withdrawn', 'Teaching Fellow Withdrawn');
    return statusMap;
  }
  
  public class ReviewStatus {
    public String preference { get; set; }
    public String status { get; set; }
    public String reviewDeadline { get; set; }
  }
  
}


 
Hi all,

I have this controller: 
public with sharing class ProfileDetailController {
  
  /*Initialization*/
  
  public ProfileDetailController(ApexPages.StandardController stdController) {
    
    Id currentContactId = UserUtils.getCurrentUserContactId();
    
    Id theProfileId = stdController.getRecord().Id;
    
    theProfile = 
      [select Id, FirstName, LastName, Site_Year__c, Email, Phone, MailingCity, MailingState, Facebook_URL__c, Twitter_URL__c, Privacy_Setting__c 
        from Contact
        where Id = :theProfileId];

    settings = [select Display__c,
                Name 
              from Breakthrough_Application_Settings__c 
              where Active__c = true LIMIT 1];
    isDisplayed = settings.Display__c;
    
    // render 'Public' view if this is rhe current user's profile (Contact) or the Privacy Setting is 'Public'
    isPublic = (theProfile.Id == currentContactId || theProfile.Privacy_Setting__c == 'Public');
    
  }
  
  /*End Initialization*/
  
  /*Properties*/
  
  public Contact theProfile { get; private set; }
  public Boolean isPublic { get; private set; }
  public Breakthrough_Application_Settings__c settings { get; set; }
  public Boolean isDisplayed { get; set; }
  
  /*End Properties*/
  
  /*Action Methods*/
  
  /*End Action Methods*/
  
  /*Helper Methods*/
  
  /*End Helper Methods*/
  
}
This is my test class:
@isTest
private class ProfileDetailControllerTest {
  
  // get full profile regardless of Privacy Setting when viewing user's own profile
  static testMethod void viewOwnProfile() {
    
    Account a = AccountUtils.createBreakthroughOrgAccount('Breakthrough Alumni', true);
    Contact c = ContactUtils.createAlumniContact('My', 'Alumnus', 'myalumnus@org.test', a.Id, false);
    c.SYSTEM_Share_Community_User__c = true;
    insert c;
    User u = UserUtils.createAlumniCommunityUser(c, false, true);
    
    // hack to workaround sharing rule
    //ContactShare cs = new ContactShare(ContactId = c.Id, UserOrGroupId = u.Id, ContactAccessLevel = 'Read');
    //insert cs;
    
    Test.startTest();
    
    System.runAs(u) {
      Test.setCurrentPage(Page.ProfileDetail);      
      Id theProfileId = stdController.getRecord().Id;
      ApexPages.StandardController stdController = new ApexPages.StandardController(c);
      ProfileDetailController ext = new ProfileDetailController(stdController);
      
      System.assertEquals(c.Id,    ext.theProfile.Id);
      System.assertEquals('Private',  ext.theProfile.Privacy_Setting__c);
      System.assertEquals(true,    ext.isPublic);
    }
    
    Test.stopTest();
    
  }
  
  // viewing profile of an alumnus with public Privacy Setting
  static testMethod void viewPublicProfile() {
    
    Account a = AccountUtils.createBreakthroughOrgAccount('Breakthrough Alumni', true);
    Contact c1 = ContactUtils.createAlumniContact('My', 'Alumnus1', 'myalumnus1@org.test', a.Id, false);
    Contact c2 = ContactUtils.createAlumniContact('My', 'Alumnus2', 'myalumnus2@org.test', a.Id, false);
    c1.SYSTEM_Share_Community_User__c = true;
    c2.SYSTEM_Share_Community_User__c = true;
    c2.Privacy_Setting__c = 'Public';
    insert new List<Contact> { c1, c2 };
    User u = UserUtils.createAlumniCommunityUser(c1, false, true);

    Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2017';
        setting.Display__c = true;
        setting.Active__c = true;
        insert setting;
    
    // hack to workaround sharing rule
    //ContactShare cs1 = new ContactShare(ContactId = c1.Id, UserOrGroupId = u.Id, ContactAccessLevel = 'Read');
    //ContactShare cs2 = new ContactShare(ContactId = c2.Id, UserOrGroupId = u.Id, ContactAccessLevel = 'Read');
    //insert new List<ContactShare> { cs1, cs2 };
    
    Test.startTest();
    
    System.runAs(u) {
      Test.setCurrentPage(Page.ProfileDetail);
      ApexPages.StandardController stdController = new ApexPages.StandardController(c2);
      ProfileDetailController ext = new ProfileDetailController(stdController);
      
      System.assertEquals(c2.Id,    ext.theProfile.Id);
      System.assertEquals('Public',  ext.theProfile.Privacy_Setting__c);
      System.assertEquals(true,    ext.isPublic);
      System.assertEquals(true, setting.Display__c);
    }
    
    Test.stopTest();
    
  }
  
  // viewing profile of an alumnus with private Privacy Setting
  static testMethod void viewPrivateProfile() {
    
    Account a = AccountUtils.createBreakthroughOrgAccount('Breakthrough Alumni', true);
    Contact c1 = ContactUtils.createAlumniContact('My', 'Alumnus1', 'myalumnus1@org.test', a.Id, false);
    Contact c2 = ContactUtils.createAlumniContact('My', 'Alumnus2', 'myalumnus2@org.test', a.Id, false);
    c1.SYSTEM_Share_Community_User__c = true;
    c2.SYSTEM_Share_Community_User__c = true;
    c2.Privacy_Setting__c = 'Private';
    insert new List<Contact> { c1, c2 };
    User u = UserUtils.createAlumniCommunityUser(c1, false, true);
    Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2017';
        setting.Display__c = true;
        setting.Active__c = true;
        insert setting;
    
    // hack to workaround sharing rule
    //ContactShare cs1 = new ContactShare(ContactId = c1.Id, UserOrGroupId = u.Id, ContactAccessLevel = 'Read');
    //ContactShare cs2 = new ContactShare(ContactId = c2.Id, UserOrGroupId = u.Id, ContactAccessLevel = 'Read');
    //insert new List<ContactShare> { cs1, cs2 };
    
    Test.startTest();
    
    System.runAs(u) {
      Test.setCurrentPage(Page.ProfileDetail);
      ApexPages.StandardController stdController = new ApexPages.StandardController(c2);
      ProfileDetailController ext = new ProfileDetailController(stdController);
      
      System.assertEquals(c2.Id,    ext.theProfile.Id);
      System.assertEquals('Private',  ext.theProfile.Privacy_Setting__c);
      System.assertEquals(false,    ext.isPublic);
      System.assertEquals(true, setting.Display__c);
    }
    
    Test.stopTest();
    
  }
  
}
I am looking for help on why I am getting this error thrown: System.QueryException: List has no rows for assignment to SObject : Class.ProfileDetailController.: line 19, column 1 Class.ProfileDetailControllerTest.viewOwnProfile: line 36, column 1

Any thoughts?
Hi everyone,

I am looking for some help with writing a test class for the below extension controller:
 
/*
 * Extension controller for calling Breakthrough Application Settings.
 *
 * HH, Breakthrough Collaborative, 2017
 */

public class ApplicationDisplayController {

	public Breakthrough_Application_Settings__c settings { get; set; }
	public Boolean isDisplayed { get; set; }

	public ApplicationDisplayController(MyProfileController ctrlParam) {
	    this.settings = [select Display__c,
	                Name 
	              from Breakthrough_Application_Settings__c 
	              where Active__c = true LIMIT 1];
	    this.isDisplayed = settings.Display__c;
	}

	public ApplicationDisplayController(AlumniSearchController ctrlParam) {
	    this.settings = [select Display__c,
	                Name 
	              from Breakthrough_Application_Settings__c 
	              where Active__c = true LIMIT 1];
	    this.isDisplayed = settings.Display__c;
	}

	public ApplicationDisplayController(JobBoardSearchController ctrlParam) {
	    this.settings = [select Display__c,
	                Name 
	              from Breakthrough_Application_Settings__c 
	              where Active__c = true LIMIT 1];
	    this.isDisplayed = settings.Display__c;
	}

	public ApplicationDisplayController(ResourceLibraryController ctrlParam) {
	    this.settings = [select Display__c,
	                Name 
	              from Breakthrough_Application_Settings__c 
	              where Active__c = true LIMIT 1];
	    this.isDisplayed = settings.Display__c;
	}
}

I am just learning Salesforce coding, so I am very shaky on writing test classes.  Thanks in advance for any help or feedback.
Hi all,

Does anyone know of a way to display or not display a Visualforce Tab in a custom Salesforce Tabs + Visualforce Page community?

This requirement would be based on whether a field value is marked as 'Display' in custom settings.  The Visualforce page has a custom controller.  Is there a way to modify my controller to only show Visualforce Tab in navigation if this field is marked?

Any ideas or suggestions are greatly appreciated!

Holly

 
Hello all,

I am struggling to write a Test Class for the following trigger and static class that synchronizes portal users with contact record data:
trigger UpdateContactFromPortalUser on User (after update) {
    //We only want to run on the single item that the user edited 
    if (Trigger.new.size()==1) 
    { 
        User u =_ Trigger.new[0]; 
        //And only if it's a portal user 
        if (u.ContactId!=null) { 
            UpdateContactFromPortalUser.updateContacts(u.Id); 
        } 
    } 
}
global class UpdateContactFromPortalUser { 
    @future 
    public static void updateContacts(String userId) {
        User u = [select ContactId,Email,FirstName,LastName,Title
                    from User
                    where Id=:userId];

        if (u!=null && u.ContactId!=null) {
            Contact c = new Contact(Id=u.ContactId,Email=u.Email,FirstName=u.FirstName,LastName=u.LastName,Title=u.Title);
            update c; 
        }
    }
}
Here is my test class code:
 
@isTest
private class UpdateContactFromPortalUserTest {

static testMethod void testUpdateContacts() {

        Test.startTest(); 
        
        User u = [select Id,ContactId,FirstName from User where ContactId<>'' limit 1]; 

        u.FirstName='Bar';
         
        update u; 

        Test.stopTest(); 

        Contact c = [select FirstName from Contact where Id=:u.ContactId]; 
        System.assertEquals(c.FirstName,u.FirstName); 
    }
}

I am getting no code coverage when I runt the test.  Can someone help point me to what I am missing?

Thanks in advance for any help.

 
Hi all,

I have the following custom lightning component, but it is coming up with the following error: Unknown controller action 'getOpps'.

component:
<aura:component controller="AcctOppsController" implements="flexipage:availableForRecordHome,force:hasRecordId">
    <aura:attribute name="mydata" type="OpportunityContactRole[]"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="currentRecordId" type="Id" />
    <aura:handler name="init" value="{!this }" action="{! c.doInit }"/>
    <div style="height: 300px">
        <lightning:datatable
                keyField="id"
                data="{! v.mydata }"
                columns="{! v.mycolumns }"
                hideCheckboxColumn="true"/>
    </div>
</aura:component>
controller:
({
    doInit: function (cmp, event, helper) {
        cmp.set('v.mycolumns', [
            {label: 'Opportunity Name', fieldName: 'opportunityId', type: 'text'},
            {label: 'Contact Name', fieldName: 'contact', type: 'text'},
            {label: 'Role', fieldName: 'role', type: 'text'},
            {label: 'Amount', fieldName: 'amount', type: 'currency'}
        ]);
        
        var fetchData = {
            opportunityId: "opportunityId",
            contact : "Contact.Name",
            role : "Role",
            amount : "Opportunity.Amount"
        };

        helper.fetchData(cmp,fetchData);
    }
})
helper:
({
    fetchData : function(cmp) {
        var recordId =  cmp.get("v.recordId");
        var action = cmp.get("c.getOpps");
        action.setParams({ "currentRecordId" : recordId });
        action.setCallback(this, $A.getCallback(function (response) {
            var state = response.getState();
            if (state ==="SUCCESS") {
                cmp.set("v.mydata", response.getReturnValue());
            } else if (state === "ERROR") {
                var errors = response.getError();
                console.error(errors);
            }
        }
                                               ));
        $A.enqueueAction(action);
    }
})
apex controller:
public with sharing class AcctOppsController{
@AuraEnabled
public String currentRecordId {get;set;}

    public AcctOppsController(ApexPages.StandardController controller) {
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
    }
    
    @AuraEnabled    
    public List<OpportunityContactRole> getOpps() {
        List<OpportunityContactRole> oppresults = [SELECT Contact.name, Role, OpportunityId, Opportunity.Amount, Opportunity.StageName, Opportunity.Type FROM OpportunityContactRole WHERE contact.accountid=:currentRecordId];
        return oppresults;
        }
}

Any thoughts on what I am missing?


 

Hi all, 
I have the below apex sharing trigger, but am struggling to get code coverage (currently at 44%):
trigger AffiliationMakePublicContactTrigger on npe5__Affiliation__c (after insert, after update, before delete) {
 
    // Get the Account Name Details
    Set<Id> AcctId = new Set<Id>();
    List<Account> AccountLists = new List<Account>();
    Map<Id,String> AccountNameMap = new Map<Id,String>();
	
    if (!Trigger.isDelete) {
		List<npe5__Affiliation__c> affiliations = [select Id, npe5__Organization__c, npe5__Organization__r.Id, Make_Public__c, npe5__Contact__r.Id from npe5__Affiliation__c where Id IN: Trigger.newMap.keyset()];
		for(npe5__Affiliation__c aff : affiliations)
		{
		 
		 if(aff.npe5__Organization__r != null)
		 {
			AcctId.add(aff.npe5__Organization__r.Id);
		 }

		}
		 
		 if(AcctId.size() > 0)
		 {
			 AccountLists  = [select Id,name from Account where Id IN: AcctId];
		 }

		for(Account acc :AccountLists  )
		{
			AccountNameMap.put(acc.id,acc.Name);
		}
		
		// Get the Group Details
		List<Group> groups = [SELECT Email,Id,Name FROM Group];

		Map<String,Id> GroupMap = new MAp<String,Id>();
		for( Group grp:groups)
		{
			if(grp.Name != null && grp.Name != '')
			{
				GroupMap.put(grp.Name,grp.Id);
			}
		}
	  
	  // inserting new records
	  if (Trigger.isInsert) {
				 
		List<ContactShare> sharesToCreate = new List<ContactShare>();

		
		for (npe5__Affiliation__c affiliation : affiliations) {
			
		  if (affiliation.Make_Public__c == true) 
		  {

			// create the new share for group
			ContactShare cs = new ContactShare();
			cs.ContactAccessLevel = 'Edit';
			cs.ContactId = affiliation.npe5__Contact__r.Id;        
			system.debug(cs.ContactId);
			if(GroupMap.containsKey(AccountNameMap.get(affiliation.npe5__Organization__r.Id)))
					cs.UserOrGroupId = GroupMap.get(AccountNameMap.get(affiliation.npe5__Organization__r.Id));   
			sharesToCreate.add(cs);

		  }
		}

		// do the DML to create shares
		if (!sharesToCreate.isEmpty())
		  insert sharesToCreate;

	  // updating existing records
	  } else if (Trigger.isUpdate) {

		List<ContactShare> sharesToCreate = new List<ContactShare>();
		List<ID> shareIdsToDelete = new List<ID>();

		for (npe5__Affiliation__c affiliation : affiliations) {

		  // if the record was public but is now private -- delete the existing share
		  if (Trigger.oldMap.get(affiliation.Id).Make_Public__c == true && affiliation.Make_Public__c == false) {
			shareIdsToDelete.add(affiliation.npe5__Contact__r.Id);

		  // if the record was private but now is public -- create the new share for the group
		  } else if (Trigger.oldMap.get(affiliation.Id).Make_Public__c == false && affiliation.Make_Public__c == true) {
			
			// create the new share with read/write access
			ContactShare cs = new ContactShare();
			cs.ContactAccessLevel = 'Edit';
			cs.ContactId = affiliation.npe5__Contact__r.Id;
			if(GroupMap.containsKey(AccountNameMap.get(affiliation.npe5__Organization__r.Id)))
					cs.UserOrGroupId =  GroupMap.get(AccountNameMap.get(affiliation.npe5__Organization__r.Id));   
			sharesToCreate.add(cs);

		  }

		}

		// do the DML to delete shares
		if (!shareIdsToDelete.isEmpty())
		  delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = 'Manual'];

		// do the DML to create shares
		if (!sharesToCreate.isEmpty())
		  insert sharesToCreate;

	  }
  }
  else if (Trigger.isDelete) {

    List<ID> shareIdsToDelete = new List<ID>();

	List<npe5__Affiliation__c> affiliations = [select Id, npe5__Organization__c, npe5__Organization__r.Id, Make_Public__c, npe5__Contact__r.Id from npe5__Affiliation__c where Id IN: Trigger.oldMap.keyset()];
    for (npe5__Affiliation__c affiliation : affiliations) {
        shareIdsToDelete.add(affiliation.npe5__Contact__r.Id);
        system.debug(shareIdsToDelete);
    }

    // do the DML to delete shares
    if (!shareIdsToDelete.isEmpty())
      delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = 'Manual'];
  }

}
Here is my test class:
@isTest
private class TestAffiliationMakePublicContactTrigger {

    // test that newly inserted records marked as pubic=true have corresponding shares created
    static testMethod void testAddShares() {
    
    Account acct = new Account(name='Breakthrough Birmingham');
        insert acct;
    Contact c = new Contact(AccountId=acct.Id, lastname='testing', firstname='apex');
        insert c;
    
    //Create Public Group
    Group gp            = new Group();
    gp.Name             = 'Breakthrough Birmingham';
    gp.DeveloperName    = 'Breakthrough_Birmingham';
    gp.Type             = 'Regular';
    insert gp;
    
    ContactShare testShare = new ContactShare();
    testShare.ContactAccessLevel = 'Edit';
    testShare.ContactId = c.Id;        
	testShare.UserOrGroupId = gp.Id;
    insert testShare;
    
    Set<ID> affiliationIds = new Set<ID>();
    List<npe5__Affiliation__c> affiliations = new List<npe5__Affiliation__c>();
    
    for (npe5__Affiliation__c aff : affiliations)
        affiliations.add(new npe5__Affiliation__c(npe5__Organization__c=acct.Id,Make_Public__c=true,npe5__Contact__c=c.Id));
		insert affiliations;
        
    for (npe5__Affiliation__c a : affiliations)
      affiliationIds.add(a.npe5__Contact__r.id);
        
    // assert that 1 share was created
    List<ContactShare> shares = [select id from ContactShare where 
      ContactId IN :affiliationIds and RowCause = 'Manual'];
    System.assertEquals(shares.size(),1);
    }

    // insert records and switch them from public = true to public = false
    static testMethod void testUpdateAffiliations() {

    Account acct = new Account(name='Breakthrough Birmingham');
        insert acct;
    Contact c = new Contact(AccountId=acct.Id, lastname='testing', firstname='apex');
        insert c;
        
    Set<ID> affiliationIds = new Set<ID>();
    List<npe5__Affiliation__c> affiliations = new List<npe5__Affiliation__c>();
    
    for (npe5__Affiliation__c aff : affiliations)
        affiliations.add(new npe5__Affiliation__c(npe5__Organization__c=acct.Id,Make_Public__c=false,npe5__Contact__c=c.Id));
		insert affiliations;
        
    for (npe5__Affiliation__c a : affiliations)
      affiliationIds.add(a.npe5__Contact__r.id);
        
    // assert that 0 shares exist
    List<ContactShare> shares = [select id from ContactShare where 
      ContactId IN :affiliationIds and RowCause = 'Manual'];
    System.assertEquals(shares.size(),0);
    
    for (npe5__Affiliation__c aff : affiliations)
      aff.Make_Public__c = true;

    update affiliations;

    // assert that 1 share was created
    shares = [select id from ContactShare where ContactId IN :affiliationIds and RowCause = 'Manual'];
    System.assertEquals(shares.size(),1);

    for (npe5__Affiliation__c aff : affiliations)
      aff.Make_Public__c = false;

    update affiliations;

    // assert that 0 shares exist
    shares = [select id from ContactShare where ContactId IN :affiliationIds and RowCause = 'Manual'];
    System.assertEquals(shares.size(),0);

    }
}

 
Hi all,

I have the below trigger, which is throwing this error: First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Contact, User/Group]: [Contact, User/Group]: Trigger.AffiliationMakePublicContactTrigger: line 64, column 1
trigger AffiliationMakePublicContactTrigger on npe5__Affiliation__c (before insert) {
 
    // Get the Account Name Details
    Set<Id> AcctId = new Set<Id>();
    List<Account> AccountLists = new List<Account>();
    Map<Id,String> AccountNameMap = new Map<Id,String>();
    
    for(npe5__Affiliation__c aff : trigger.new)
    {
     
     if(aff.npe5__Organization__r != null)
     {
        AcctId.add(aff.npe5__Organization__r.Id);
     }

    }
     
     if(AcctId.size() > 0)
     {
         AccountLists  = [select Id,name from Account where Id IN: AcctId];
     }

    for(Account acc :AccountLists  )
    {
        AccountNameMap.put(acc.id,acc.Name);
    }
    
    // Get the Group Details
    List<Group> groups = [SELECT Email,Id,Name FROM Group];

    Map<String,Id> GroupMap = new MAp<String,Id>();
    for( Group grp:groups)
    {
    	if(grp.Name != null && grp.Name != '')
    	{
        	GroupMap.put(grp.Name,grp.Id);
    	}
    }
  
  // inserting new records
  if (Trigger.isInsert) {
             
    List<ContactShare> sharesToCreate = new List<ContactShare>();

    for (npe5__Affiliation__c affiliation : Trigger.new) {
        
      if (affiliation.Make_Public__c == true) 
      {

        // create the new share for group
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = affiliation.npe5__Contact__r.Id;        
        system.debug(cs.ContactId);
        if(GroupMap.containsKey(AccountNameMap.get(affiliation.npe5__Organization__r.Id)))
                cs.UserOrGroupId = GroupMap.get(AccountNameMap.get(affiliation.npe5__Organization__r.Id));   
        sharesToCreate.add(cs);

      }
    }

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  // updating existing records
  } else if (Trigger.isUpdate) {

    List<ContactShare> sharesToCreate = new List<ContactShare>();
    List<ID> shareIdsToDelete = new List<ID>();

    for (npe5__Affiliation__c affiliation : Trigger.new) {

      // if the record was public but is now private -- delete the existing share
      if (Trigger.oldMap.get(affiliation.Id).Make_Public__c == true && affiliation.Make_Public__c == false) {
        shareIdsToDelete.add(affiliation.Id);

      // if the record was private but now is public -- create the new share for the group
      } else if (Trigger.oldMap.get(affiliation.Id).Make_Public__c == false && affiliation.Make_Public__c == true) {
        
        // create the new share with read/write access
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = affiliation.npe5__Contact__r.Id;
        if(GroupMap.containsKey(AccountNameMap.get(affiliation.npe5__Organization__r.Id)))
                cs.UserOrGroupId =  GroupMap.get(AccountNameMap.get(affiliation.npe5__Organization__r.Id));   
        sharesToCreate.add(cs);

      }

    }

    // do the DML to delete shares
    if (!shareIdsToDelete.isEmpty())
      delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = 'Manual'];

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  }

}
I have the affiliation object (from NPSP), and it creates the following records with these fields: organization affiliation (account lookup), contact (contact lookup) and 'make public' field. 
I want to share the contact (contact lookup) from the affiliation record with a specified public group whether that happens on insert or on update.  
Any thoughts on what I am missing?
 
Hi All,

I have the below trigger, and what I want to do is pull in the name of the group based on a field on the contact record where the after insert/after update is taking place.  The field is an account lookup field on contact and is named: Acct__c.  I want this to happen dynamically vs. having to hard code the name of the group.
trigger ContactMakePublicTrigger on Contact (after insert, after update) {
  
  ID groupId = [select id, Name from Group where Name = 'Cincinati User'].id;
    
  // inserting new records
  if (Trigger.isInsert) {
	         
    List<ContactShare> sharesToCreate = new List<ContactShare>();

    for (Contact contact : Trigger.new) {
        
      if (contact.Make_Public__c == true) {

        // create the new share for group
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = contact.Id;
        cs.UserOrGroupId =  groupId;
        sharesToCreate.add(cs);

      }
    }

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  // updating existing records
  } else if (Trigger.isUpdate) {

    List<ContactShare> sharesToCreate = new List<ContactShare>();
    List<ID> shareIdsToDelete = new List<ID>();

    for (Contact contact : Trigger.new) {

      // if the record was public but is now private -- delete the existing share
      if (Trigger.oldMap.get(contact.id).Make_Public__c == true && contact.Make_Public__c == false) {
        shareIdsToDelete.add(contact.id);

      // if the record was private but now is public -- create the new share for the group
      } else if (Trigger.oldMap.get(contact.id).Make_Public__c == false && contact.Make_Public__c == true) {
        
        // create the new share with read/write access
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = contact.Id;
        cs.UserOrGroupId =  groupId;
        sharesToCreate.add(cs);

      }

    }

    // do the DML to delete shares
    if (!shareIdsToDelete.isEmpty())
      delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = 'Manual'];

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  }

}
Any thoughts on how to rework the trigger to get the name of the lookup field dynamically?