• Nayana K
  • PRO
  • 4909 Points
  • Member since 2014
  • Senior Software Engineer
  • V2Force


  • Chatter
    Feed
  • 148
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 5
    Questions
  • 779
    Replies
Hi Everyone,

I am currently trying to get a test to work for a simple dynamic apex query.

However, I am getting nothing back when running the test.

Could someone please offer some assistance?

Below is my controller
 
public class UserInfo { 
    Public List<User> getUserInfo() {
       List<User> UserInfo=[Select Name,Kolbe_Score__c,Verb__c,Question_1__c,Question_1_Answer__c,Question_2__c,Question_2_Answer__c,Question_3__c,Question_3_Answer__c,Question_4__c,Question_4_Answer__c,Question_5__c,Question_5_Answer__c,Question_6__c,Question_6_Answer__c,User_Bio_Image_ID__c
                                                      From User                                                     
                                                      Where id = :ApexPages.currentPage().getParameters().get('sfdc.userId') ];
                                                    
                                                                                          
        return UserInfo;
  }
}

My Test
@isTest
public class UserInfoTest 
{ 
    public static testMethod void TestMethod1() 
    {
        User U = new User();
        U.Kolbe_Score__c= 'Test';
        insert U;
        
        
        Test.StartTest(); 

        PageReference pageRef = Page.UserInfoVF; 
        pageRef.getParameters().put('id', String.valueOf(U.Id));
        Test.setCurrentPage(pageRef);

        UserInfo testAccPlan = new UserInfo();
  
        //testAccPlan.save(); call all your function here
        Test.StopTest();
        
    }
   
}


My Visualforce Page is called UserInfoVF

Thank you in advance for your help!
Sorry for the really long post, but I am a struggling solo admin trying to make sense of some Apex. I have been getting a lot of errors with various (VERY SIMPLE) process builders, and at Salesforce World Tour Boston, some developers suggested that it may be causing some sort of loop with an existing trigger/Apex in our instance. (I'm getting the "Too many SOQL queries" errors very often, mostly with bulk lead imports). 

We have quite a few managed packages, but only 2 triggers, and 3 Apex classes that were created in-house by a consultant before I started at my company. I have documentation on what exactly it does, and we are willing to remove the functionality that these perform, and just want to get rid of them. 

I tried deactivating the 2 triggers in sandbox and push them to production but got many test failures. So I assumed that I also need to do something with the Apex classes, and found the suggestion to "comment out" the entire thing on another post here in the community.

So my question is how to do that. I tried adding /* at the very beggining and */ at the end, but that gave me the error below. Any help would be GREATLY appreciated. I'm looking forward to learning some of this stuff on my own, but we need to get this done ASAP. 

Best,
Steph

User-added image

And here are the specifics of the Trigger and Apex class code if that is helpful:

EventTrigger 
trigger EventTrigger on Event (after insert, after update) {

    EventTriggerHandler handler = new EventTriggerHandler();

    if (Trigger.isAfter && Trigger.isInsert) {
        handler.afterInsert(Trigger.new);
    } else if (Trigger.isAfter && Trigger.isUpdate) {
        handler.afterUpdate(Trigger.oldMap, Trigger.newMap, Trigger.new);
    }

}

TaskTrigger:
trigger TaskTrigger on Task (after insert, after update) {

    TaskTriggerHandler handler = new TaskTriggerHandler();

    if (Trigger.isAfter && Trigger.isInsert) {
        handler.afterInsert(Trigger.new);
    } else if (Trigger.isAfter && Trigger.isUpdate) {
        handler.afterUpdate(Trigger.oldMap, Trigger.newMap, Trigger.new);
    }

}

ProsepctManagement (Apex Class)
public with sharing class ProspectManagement {

    public static final Set<String> SALES_TASK_TYPES = new Set<String> {
        'Call', 'Email - Sent', 'Email - Opened', 'Email - Clicked', 'Other'
    };

    public static final Set<String> SALES_EVENT_TYPES = new Set<String>{
        'Scheduled Call - Sales', 'Demo', 'Scheduled Call - Cust Success', 'In-person Meeting', 'Other'
    };
    
    private final DateTime NOW;
    private Map<ID, Lead> leads;
    private Map<ID, Contact> contacts;
    
    public ProspectManagement(Set<ID> entityIds) {
        this.leads = this.getLeads(entityIds);
        this.contacts = this.getContacts(entityIds);
        NOW = DateTime.now();
    }
    
    public ProspectManagement(Map<ID, Lead> leads, Map<ID, Contact> contacts) {
        this.leads = leads;
        this.contacts = contacts;
        NOW = DateTime.now();
    }
    
    public Map<ID, Lead> getLeads() {
        return this.leads;
    }
    
    public Map<ID, Contact> getContacts() {
        return this.contacts;
    }
    
    private Map<ID, Lead> getLeads(Set<ID> leadIds) {
        return new Map<ID, Lead>([
            SELECT Id, First_Connect_Date__c, First_Connect_Touch__c, First_Sales_Activity_Date__c,
                Total_Completed_Touches__c
            FROM Lead
            WHERE Id IN :leadIds
        ]);
    }
    
    private Map<ID, Contact> getContacts(Set<ID> contactIds) {
        return new Map<ID, Contact>([
            SELECT Id, First_Connect_Date__c, First_Connect_Touch__c, First_Sales_Activity_Date__c,
                Total_Completed_Touches__c, AccountId
            FROM Contact
            WHERE Id IN :contactIds
        ]);
    }
    
    /**
     * Updates the First_Sales_Activity_Date__c field to now if it wasn't previously set.
     */
    public void updateFirstSalesActivityDateTime(ID entityId) {    
        if (entityId.getSObjectType() == Contact.SObjectType && 
            this.contacts.get(entityId).First_Sales_Activity_Date__c == null) {
            Contact c = this.contacts.get(entityId);
            if (c.First_Sales_Activity_Date__c == null) {
                c.First_Sales_Activity_Date__c = DateTime.now();
            }
        } else if (entityId.getSObjectType() == Lead.SObjectType && 
            this.leads.get(entityId).First_Sales_Activity_Date__c == null) {
            Lead l = leads.get(entityId);
            if (l.First_Sales_Activity_Date__c == null) {
                l.First_Sales_Activity_Date__c = DateTime.now();
            }
        }    
    }
    
    /**
     * Updates leads and contacts, the IDs of which are in entityIds, such that Last_Contacted_Date__c is now.
     * If a Contact has an Account, the Last_Contacted_Date__c field on the Account is also updated.
     * THIS METHOD EXECUTES A DML STATEMENT.
     */
    public void updateLastContactedDate(Set<ID> entityIds) {
        System.debug('Entity IDs: ' + entityIds);
        Set<ID> accountIds = new Set<ID>();
        for (ID entityId: entityIds) {
            if (this.leads.containsKey(entityId)) {
                System.debug('upating lead ' + entityId);
                this.leads.get(entityId).Last_Contacted_Date__c = NOW;
            } else if (this.contacts.containsKey(entityId)) {
                this.contacts.get(entityId).Last_Contacted_Date__c = NOW;
                System.debug('updating contact ' + entityId);
                if (this.contacts.get(entityId).AccountId != null) {
                    accountIds.add(this.contacts.get(entityId).AccountId);
                }
            }
        }
        System.debug('Account IDs: ' + accountIds);
        
        List<Account> accounts = [SELECT Id, Last_Contacted_Date__c FROM Account WHERE Id in :accountIds];
        for (Account a: accounts) {
            a.Last_Contacted_Date__c = NOW;
        }
        
        update accounts;
    }
    
    /**
     * Updates Total_Completed_Touches__c on Leads and Contacts if the ID is contained in entityIds.
     */
    public void updateTotalCompletedTouches(Set<ID> entityIds) {       
        List<AggregateResult> countsPerEntity =([
            SELECT Who.Id entityId, Count(ID)
            FROM Task
            WHERE Cancelled__c = false AND
                Status = 'Completed' AND
                Type IN :SALES_TASK_TYPES AND
                Who.Id IN :entityIds
            GROUP BY Who.Id
        ]);
        countsPerEntity.addAll([
            Select Who.Id entityId, Count(ID)
            FROM Event
            WHERE Cancelled__c = false AND
                StartDateTime <= :now AND
                Type IN :SALES_EVENT_TYPES AND
                Who.Id in :entityIds
            GROUP BY Who.Id
        ]);
        
        Set<ID> entitiesTouched = new Set<ID>();
        for (AggregateResult result: countsPerEntity) {
            ID entityId = (ID) result.get('entityId');
            Integer count = Integer.valueOf(result.get('expr0'));
            if (entityId.getSObjectType() == Contact.SObjectType) {
                Contact c = contacts.get(entityId);
                if (entitiesTouched.contains(entityId)) {
                    c.Total_Completed_Touches__c += count;
                } else {
                    c.Total_Completed_Touches__c = count;
                    entitiesTouched.add(entityId);
                }
            } else if (entityId.getSObjectType() == Lead.SObjectType) {
                Lead l = leads.get(entityId);
                if (entitiesTouched.contains(entityId)) {
                    l.Total_Completed_Touches__c += count;
                } else {
                    l.Total_Completed_Touches__c = count;
                    entitiesTouched.add(entityId);
                }
            }
        }
    }
    
    /**
     * entityIds is a set of IDs of Contacts and Leads associated with a Task where First_Connect__c is set to true.
     */
    public void updateFirstConnectInfo(Set<ID> entityIds) {
        // Count matching tasks and events, and group by the Who.Id
        
        // TODO: Comments from Maggie say we should account for this on a PER ENTITY basis, where we basically have to
        // replay all tasks and events to figure out when the earliest task or event labeled first_connect exists.
        
        // Get eligible leads and contacts associated with the First_Contact__c tasks.
        
        Set<ID> allIds = new Set<ID>();
        // Filter out any entity ids where we've already connected for the first time.
        for (ID leadId: this.leads.keySet()) {
            Lead l = this.leads.get(leadId);
            if (l.First_Connect_Date__c == null && l.First_Connect_Touch__c == null && entityIds.contains(leadId)) {
                allIds.add(leadId);
            }
        }
        for (ID contactId: this.contacts.keySet()) {
            Contact c = this.contacts.get(contactId);
            if (c.First_Connect_Date__c == null & c.First_Connect_Touch__c == null && entityIds.contains(contactId)) {
                allIds.add(contactId);
            }
        }
        
        List<AggregateResult> countPerEntity = [
            SELECT Who.Id entityId, Count(ID)
            FROM Task
            WHERE Cancelled__c = false AND
                Status = 'Completed' AND
                Type IN :SALES_TASK_TYPES AND
                Who.Id IN :allIds
            GROUP BY Who.Id
        ];
        countPerEntity.addAll([
            Select Who.Id entityId, Count(ID)
            FROM Event
            WHERE Cancelled__c = false AND
                StartDateTime <= :now AND
                Type IN :SALES_EVENT_TYPES AND
                Who.Id in :allIds
            GROUP BY Who.Id
        ]);

        // Since there may be two AggregateResults per WhoId, acknowledge when we've SET the value, so next time
        // We increment the value instead.
        Set<ID> entitiesTouched = new Set<ID>();
        for (AggregateResult entityTasks: countPerEntity) {
            ID entityId = (ID) entityTasks.get('entityId');
            Integer count = Integer.valueOf(entityTasks.get('expr0'));
            if (leads.containsKey(entityId)) {
                Lead l = leads.get(entityId);
                if (entitiesTouched.contains(entityId)) {
                    l.First_Connect_Touch__c += count;
                } else {
                    l.First_Connect_Touch__c = count;
                    l.First_Connect_Date__c = now;
                    entitiesTouched.add(entityId);
                }
            } else if (contacts.containsKey(entityId)) {
                Contact c = contacts.get(entityId);
                if (entitiesTouched.contains(entityId)) {
                    c.First_Connect_Touch__c += count;
                } else {
                    c.First_Connect_Touch__c = count;
                    c.First_Connect_Date__c = now;
                    entitiesTouched.add(entityId);
                }
            }
        }
    }
    
    public void updateTotalSalesTouches() {
        // Sum all open and completed tasks of the appropriate types.
        // This includes cancelled touches, per mfitzgerald.
        
        Set<ID> allIds = new Set<ID>();
        // Get eligible leads and contacts associated with the First_Contact__c tasks.
        for (Lead l: this.leads.values()) {
            allIds.add(l.id);
        }
        for(Contact c: this.contacts.values()) {
            allIds.add(c.id);
        }

        List<AggregateResult> tasksPerEntity = [
            SELECT Who.Id entityId, Count(ID)
            FROM Task
            WHERE
                Type IN :SALES_TASK_TYPES AND
                Who.Id IN :allIds
            GROUP BY Who.Id
        ];
        List<AggregateResult> eventsPerEntity = [
            Select Who.Id entityId, Count(ID)
            FROM Event
            WHERE
                Type IN :SALES_EVENT_TYPES AND
                Who.Id in :allIds
            GROUP BY Who.Id
        ];

        // Condense the values of these maps into single values per ID, and stamp those onto the appropriate entity.
        Map<ID, Integer> counts = new Map<ID, Integer>();
        for (AggregateResult agg: tasksPerEntity) {
            counts.put((ID) agg.get('entityId'), Integer.valueOf(agg.get('expr0')));
        }

        for (AggregateResult agg: eventsPerEntity) {
            Integer count = Integer.valueOf(agg.get('expr0'));
            ID entityId = (ID) agg.get('entityId');
            if (counts.containsKey(entityId)) {
                counts.put(entityId, counts.get(entityId) + count);
            } else {
                counts.put(entityId, count);
            }
        }
        
        for (ID leadId: this.leads.keySet()) {
            if (counts.containsKey(leadId)) {
                this.leads.get(leadId).Total_Sales_Touches__c = counts.get(leadId);
            }
        }
        for (ID contactId: this.contacts.keySet()) {
            if (counts.containsKey(contactId)) {
                this.contacts.get(contactId).Total_Sales_Touches__c = counts.get(contactId);
            }
        }
    }
    
    public static Boolean isTaskAllowed(Task t) {
        return SALES_TASK_TYPES.contains(t.Type);
    }
    
    public static Boolean isEventAllowed(Event e) {
        return SALES_EVENT_TYPES.contains(e.Type);
    }
    
    public static Boolean taskJustCompleted(Task oldT, Task newT) {
        return oldT.Status != 'Completed' && newT.Status == 'Completed';
    }
    
    public static Boolean eventJustCompleted(Event oldE, Event newE) {
        return !oldE.Event_Completed__c && newE.Event_Completed__c;
    }

    @future
    public static void handleTasksAndEventsWithNoWhoId(Set<ID> activityIds) {
        List<Task> tasks = [
            SELECT WhoId, Status, Type, Cancelled__c, First_Connect__c
            FROM Task 
            WHERE Id IN :activityIds
        ];
        List<Event> events = [
            SELECT WhoId, Event_Completed__c, Type, Cancelled__c, First_Connect__c
            FROM Event
            WHERE Id IN :activityIds
        ];
        
        if (tasks.size() > 0) {
            TaskTriggerHandler taskHandler = new TaskTriggerHandler(true);
            taskHandler.afterInsert(tasks);       
        }
        
        if (events.size() > 0) {
            EventTriggerHandler eventHandler = new EventTriggerHandler(true);
            eventHandler.afterInsert(events);
        }
    }
}
EventTriggerHandler (Apex Class)
public with sharing class EventTriggerHandler {

    private ProspectManagement prospectManager;
    private Boolean isFutureContext = false;
    
    public EventTriggerHandler() {
    
    }
    
    public EventTriggerHandler(Boolean isFuture) {
        this.isFutureContext = isFuture;
    }
    
    public void afterInsert(List<Event> newEvents) {
        Set<ID> allIds = new Set<ID>();
        List<Event> validEvents = new List<Event>();
        Set<ID> eventsWithoutTargets = new Set<ID>();
        for (Event e: newEvents) {
            if (!ProspectManagement.isEventAllowed(e)) {
                continue;
            }
            if (e.WhoId == null) {
                eventsWithoutTargets.add(e.Id);
                continue;
            }
            allIds.add(e.WhoId);
            validEvents.add(e);
        }

        this.prospectManager = new ProspectManagement(allIds);
        
        this.prospectManager.updateTotalSalesTouches();
        this.updateFirstConnectInfo(validEvents);
        this.updateFirstSalesActivityDateTimeOnInsert(validEvents);
        this.updateTotalCompletedTouchesOnInsert(validEvents);
        this.updateLastContactedDateOnInsert(validEvents);
        
        update this.prospectManager.getLeads().values();
        update this.prospectManager.getContacts().values();
        
        if (!this.isFutureContext && eventsWithoutTargets.size() > 0) {
            ProspectManagement.handleTasksAndEventsWithNoWhoId(eventsWithoutTargets);
        }
    }

    public void afterUpdate(Map<ID, Event> oldMap, Map<ID, Event> newMap, List<Event> newEvents) {
        Set<ID> allIds = new Set<ID>();
        List<Event> validEvents = new List<Event>();
        Map<ID, Event> oldValidEvents = new Map<ID, Event>();
        Map<ID, Event> newValidEvents = new Map<ID, Event>();
        for (Event e: newEvents) {
            if (e.WhoId == null || !ProspectManagement.isEventAllowed(e)) {
                continue;
            }
            allIds.add(e.WhoId);
            validEvents.add(e);
            oldValidEvents.put(e.Id, oldMap.get(e.Id));
            newValidEvents.put(e.Id, newMap.get(e.Id));
        }

        this.prospectManager = new ProspectManagement(allIds);
        this.updateFirstConnectInfo(validEvents);
        this.updateFirstSalesActivityDateTimeOnUpdate(oldValidEvents, newValidEvents);
        this.updateTotalCompletedTouchesOnUpdate(oldValidEvents, newValidEvents);
        this.updateLastContactedDateOnUpdate(oldValidEvents, newValidEvents);
        
        update this.prospectManager.getLeads().values();
        update this.prospectManager.getContacts().values();
    }
    
    /**
     * When a Task or Event is updated to have “First Connect?” = True (manually set by Sales Rep when logging calls
     * and emails), find the Lead or Contact referenced in the “Name” (Who) field, and set the following fields on 
     * that Lead or Contact record only if they are currently blank (we’re looking at FIRST time this happens):
     *     First Connect Touch Number = Get all completed activities associated to the Lead/Contact, ordered by due 
     *         date or event start date, and count the number of activities before and including the first activity 
     *         where Connect = true
     *     First Connect DateTime = Set NOW
     */
    private void updateFirstConnectInfo(List<Event> events) {
        Set<ID> allIds = new Set<ID>();
        Set<ID> updatedEntities = new Set<ID>();
        Set<ID> firstConnectTaskEntities = new Set<ID>();

        // Accumulate the entities associated with First_Contact__c tasks.
        for (Event e: events) {
            if (e.First_Connect__c) {
                firstConnectTaskEntities.add(e.WhoId);
            }
        }
        
        this.prospectManager.updateFirstConnectInfo(firstConnectTaskEntities);
    }
    
    
    /**
     * When a Task is updated to Status = Completed OR an Event startdate time is in the past and Cancelled = false,
     * find the Lead or Contact referenced in the “Name” (Who) field, and if the First Sales Activity Datetime field 
     * is blank, set NOW
     */
    private void updateFirstSalesActivityDateTimeOnInsert(List<Event> events) {
        for (Event e: events) {
            if (e.Event_Completed__c && !e.Cancelled__c) {
                this.prospectManager.updateFirstSalesActivityDateTime(e.WhoId);
            }
        }
    }
    
    /**
     * When a Task is updated to Status = Completed OR an Event startdate time is in the past and Cancelled = false,
     * find the Lead or Contact referenced in the “Name” (Who) field, and if the First Sales Activity Datetime field 
     * is blank, set NOW.
     */
    private void updateFirstSalesActivityDateTimeOnUpdate(Map<ID, Event> oldEvents, Map<ID, Event> newEvents) {
        for (ID eventId: newEvents.keySet()) {
            Event e = newEvents.get(eventId);
            if (ProspectManagement.eventJustCompleted(oldEvents.get(eventId), e)) {
                this.prospectManager.updateFirstSalesActivityDateTime(e.WhoId);    
            }
        }
    }

    /**
     * When a Task is updated to Status = Completed OR an Event startdate time is in the past and Cancelled = false,
     * find the Lead or Contact referenced in the “Name” (Who) field,
     * count all related activities that are “completed” (ignore open tasks and future events), and stamp the number in 
     * this field.
     */    
    private void updateTotalCompletedTouchesOnInsert(List<Event> newEvents) {
        Set<ID> entityIds = new Set<ID>();
        for (Event e: newEvents) {
            if (e.Event_Completed__c && !e.Cancelled__c) {
                entityIds.add(e.WhoId);
            }
        }
        this.prospectManager.updateTotalCompletedTouches(entityIds);
    }

    /**
     * When a Task is updated to Status = Completed OR an Event startdate time is in the past and Cancelled = false,
     * find the Lead or Contact referenced in the “Name” (Who) field,
     * count all related activities that are “completed” (ignore open tasks and future events), and stamp the number in 
     * this field.
     */
    private void updateTotalCompletedTouchesOnUpdate(Map<ID, Event> oldEvents, Map<ID, Event> newEvents) {
        Set<ID> entityIds = new Set<ID>();
        for (ID eventId: oldEvents.keySet()) {
            Event e = newEvents.get(eventId);
            if (ProspectManagement.eventJustCompleted(oldEvents.get(eventId), e)) {
                entityIds.add(newEvents.get(eventId).WhoId);
            }
        }
        this.prospectManager.updateTotalCompletedTouches(entityIds);
    }
    
    private void updateLastContactedDateOnInsert(List<Event> newEvents) {
        Set<ID> entityIds = new Set<ID>();
        for (Event e: newEvents) {
            if (e.Event_Completed__c && !e.Cancelled__c) {
                entityIds.add(e.WhoId);
            }
        }
        this.prospectManager.updateLastContactedDate(entityIds);
    }

    /**
     * When an activity is updated to Status = Completed OR an Event startdate time is in the past and
     * Cancelled = false, find the Lead or Contact referenced in the “Name” (Who) field, and update Last Reach Out Date to NOW
     * Also find the Account associated, and update Last Contacted Date to NOW
     */
    private void updateLastContactedDateOnUpdate(Map<ID, Event> oldEvents, Map<ID, Event> newEvents) {        
        Set<ID> entityIds = new Set<ID>();
        for (ID eventId: oldEvents.keySet()) {
            Event e = newEvents.get(eventId);
            if (ProspectManagement.eventJustCompleted(oldEvents.get(eventId), e)) {
                entityIds.add(e.WhoId);
            }
        }
        this.prospectManager.updateLastContactedDate(entityIds);   
    }       
}

TaskTriggerHandler (Apex Class) - Very similar to the EventTriggerHandler, but my post is already too long so I can't add it! 

 
I have the following class which fails to get code coverage on lines in bold. I have searched through the forums and can't determine how to get those particular lines covered. 

public without sharing class projectWizardController {

Project__c project;

   public Project__c getProject() {
      if(project == null) project = new Project__c();
      project.Plan__c = ApexPages.currentPage().getParameters().get('planId');
      project.Status__c = 'New';
      return project;
   }    
   
   public PageReference step1() {      
      return Page.new_project_p1;
   }
   
   public PageReference step2() {      
      return Page.new_project_p2;
   }
   
   public PageReference step3() {      
      return Page.new_project_p3;
   }
             
   public PageReference submit() {

      try {     
          //if(project.get('Id') == null) 
          project.Status__c = 'Submitted';
          project.Submitted__c = Date.Today();
          insert project;
          PageReference projectPage = new PageReference('/apex/manage_project?id=' + project.id + '&planId='+          ApexPages.currentPage().getParameters().get('planId'));
          projectPage.setRedirect(true);         
          return projectPage;

    
        }
      catch (Exception e) {apexpages.addmessages(e);}return null;

     }         
}

The test class is below.
@isTest
public class projectWizardControllerTest {
  private static testmethod void testSubmittedProject() {
 
    projectWizardController controller = new projectWizardController(); 

    //ARRANGE    
    Plan__c plan = new Plan__c();insert plan;
    Project__c project = controller.getProject();
    project.Plan__c = plan.id;
    project.Status__c = 'Submitted';
    insert project;
    
    //ACT
    Test.startTest();
        controller.step1();
        controller.step2();
        controller.step3();                
        controller.submit();           
        PageReference pageRef = Page.manage_project;
        Test.setCurrentPage(pageRef);
        ApexPages.currentPage().getParameters().put('planid',plan.id);
        ApexPages.currentPage().getParameters().put('id',project.id);
        ApexPages.currentPage().setRedirect(true);        
    Test.stopTest();        
    //ASSERT
    System.assertEquals(project.Status__c, 'Submitted');         
}
}
Hi All,

Im getting an error like Expecting '}' but was: 'trigger'. Can you help me with this one? Thanks!

@isTest
public class TestRestrictContactByName {

trigger RestrictContactByName on Contact (before insert) {
//check contacts prior to insert or update for invalid data
    For (Contact c : Trigger.New) {
        if(c.LastName == 'INVALIDNAME') {   //invalidname is invalid
            c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML');
        }

    }

}
}
Hello Developers,

I am writing small method in apex class which will use in lightning component. I am following lightning syntax still I am getting compile error. PFB the code snippet which throwing the error.
 
@AuraEnabled public Contact cont{get;set;} 
​@AuraEnabled
 public static id getDetails(){
     Id aa='sss';
     System.debug('caseObjh.Order:::>'+cont.Order_Num__c);
     return aa;
  }
I have referred below link still don't have any clue on this error.
https://salesforce.stackexchange.com/questions/172265/can-we-access-auraenabled-variables-in-auraenabled-methods?rq=1
 
Can you please help me.  Thanks

Regards,
Sagar
 
Message : Challenge Not yet complete... here's what's wrong: 
Could not find a sharing solution 'Volunteerism Board'.

I made this :

User-added image



User-added image





Maybe.. I think problem is 
" Also, provide edit access to this field on an individual-by-individual basis without modifying profiles. Call this solution "Volunteerism Board". "

How can I do?
I am working on the App Customization Specialist Superbadge and this one has me baffled. Here is the part I'm stuck on...

Quick Self Sign Up
Maria asked for a quick way for users to sign themselves up for a Shift directly from a Volunteer Shift record. Your solution was an action with the label Sign Me Up. To keep it simple there should be no fields on the pop-up. Instead the action automatically sets the Volunteer to the user clicking the button, changes the status to Confirmed, and assigns the currently viewed Shift as the new record's Volunteer Shift. Once the action is done show the friendly message "Congratulations, you are signed up!".

Based on what I'm reading, they seem to be asking me to create a Quick Action button that creates a new record with the necessary fields set to default values. The problem is that two of the fields that are required are Lookups that I was required to create in the first challenge. One to supply the User Name and another to supply the Volunteer Shift Name. Quick Action default values can't populate Lookup fields, right? I tried creating a flow, but you can't trigger an autolaunched flow from a Quick Action, only Screen Flows. The challenge wants one button click and it's done. Can someone tell me what I'm missing here?
Hi there,

I got following error.

Each article record type must contain the Question, Answer, and Record Type fields. Knowledge users must have the ability to select a record type when creating or editing articles.

What is wrong with following settings.
User-added image
Thanks & Regards,
LinThaw
Hi,

I am displaying my Object's fields to the users like below. I have given a checkbox against each value. On click of submit, I want to use the selected values only and use them (say save to the DB).

User-added image

Following is the apex code :
 
              <apex:pageblockTable value="{!filteredReq}" var="req"  >
                    <!--<apex:pageBlockTable value="{!FG_Business_Requirement__c}" var="c" id="table1"/> -->
                    <!-- <apex:column >-->
                    <!--   <apex:param value="{!req.BR_Number__c}" assignTo="{!currentReqNum}" />-->
                    <!--    <apex:selectCheckboxes value="{!brNumbers}">-->
                    <!--       <apex:selectOptions value="{!reqItems}" />-->
                    <!--   </apex:selectCheckboxes>-->
                    <!--  </apex:column>-->
                    
                    <apex:column >
                        <apex:param value="{!req}" assignTo="{!reqList[count].con}" />
                        <!-- <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>-->
                        <apex:inputCheckbox value="{!selected}" />
                    </apex:column>
                    <apex:column style="text-align: justify;" value="{!req.BR_Number__c}"/>
                    <apex:column style="text-align: justify;" value="{!req.Name}"/>
                    <apex:column style="text-align: justify;" value="{!req.FG_id__c}"/>
                    <apex:column style="text-align: justify;" value="{!req.BR_Complexity__c}"/>
                    <apex:column style="text-align: justify;" value="{!req.Tech_Complexity__c}"/>
                    <apex:column style="text-align: justify;" value="{!req.BSRQ_Process__c}"/>
                    <apex:column style="text-align: justify;" value="{!req.BSRQ_Process_Group__c}"/>
                    <apex:column style="text-align: justify;" value="{!req.BSRQ_SubProcess__c }"/>
                    
                    <apex:param value="{!++count}" assignTo="{!count}"/>
                </apex:pageblockTable>
                <apex:commandButton value="Submit" action="{!submit}" dir="LTR"/>

Can anybody tell me if there is a way I can link the checkbox with an Object or even a String that will help me get hold of the selected list and then submit the selected values only?

Thanks,
Mayank Batra


 
I'm having process builder in my org for autocalculation of some fields. Now I have to replace that process builder with code. So I have written code for that but unable to insert fields after any DML operation.Below is my code for the same. data should automatically inser in field 'Exposure_at_Default__c' from  field Limit__c 
*******
trigger EAD_Calculator on Facility__c (after insert, after update) {
    Facility__c[] facList = new Facility__c[] {};
        
        //if (trigger.isAfter){
            if (trigger.isUpdate || trigger.isInsert){
                for (Facility__c fac: Trigger.new) {
                    Facility__c newFac = new Facility__c(id= fac.Id);
                     if(newFac.Limit__c != null){
                            newFac.Exposure_at_Default__c = newFac.Limit__c;
                         system.debug('Limit__c' +newFac.Limit__c);
                         system.debug('Exposure_at_Default__c' +newFac.Exposure_at_Default__c);
                     facList.add(newFac);
               }
            }
         }
      upsert facList;
    }
  • April 03, 2018
  • Like
  • 0
Hi! 

Im 100% new to working with SalesForce. But it seems like a really interesting thing to be working with. 
Right now im going to implement SalesForce with my node app. The thing i want to show in my node application is a list of the current logged in users business-opportunities. I have been searching the forum with nerly zero succes and now im asking you guys!(who seem to be very helpful and friendly). In my head i just make a http-get call in my application and then write the opportunites out in a list. But i cant make it work.. Im up for any ideas so feel free to send me any kind of message or post somthing here. I think im just in need of some guidance.
Cheers!
  • April 03, 2018
  • Like
  • 0
Stuck on this. I'm assuming it's referring to the field filter on Volunteer Organization on the Volunteer Activity object (which restricts a new Volunteer Activity record to being associated only with any Volunteer Organizations that are Accepting Activities).

I currently have the filter set to 
Volunteer Organization: Volunteer Organization StatusEQUALSAccepting Activities. This seems right to me. Anybody else see this and have any suggestions?
I'm getting an error, 

Challenge Not yet complete... here's what's wrong: 
The 'IsShiftVolunteer' field formula on the 'Volunteer Shift Workers' is not resulting in a check box when the logged in user is the volunteer, and unchecked when they are not.

I did check with two users and two volunteer shift worker records, and it works as expected. 

I entered the forumla as 
!ISBLANK(Volunteer__r.Id) && $User.Id = Volunteer__r.Id
I'm not sure what I'm missing here.
 
Hi everyone, I am stuck on the App Customization Superbadge. I have been attempting to create a rollup summary field for shifts taken which filters only records that have a status of completed or confirmed, however, with rollup summary fields, I can only use AND logic, not OR, thus triggering this error message when I attempt to calculate the number of available shifts against desired shifts.

Challenge Not yet complete... here's what's wrong: 
The '# of Volunteers Still Needed' field on the 'Volunteer Shift' record is not working as expected.

Is there anything I am missing?

 
Hi,
Can someone please help with the sample code snippet for trigger:
Hi Have three objects - (A , B and C).
I have an external system that is creating a single record in object C and bulk of records in object B. I want a trigger that as soon as a record is inserted or updated in obejct C, copy the record values from object B and insert/update it in Object A.

Thanks.
Hi! Im trying resolve a search issue in opportunity to search records for a particular object custom object.  When I press the search I get this error.
User-added image

I looked at the APEX code and it looks fine using the FROM syntax.  
 
public void searchSpace2() {
        try {
            String spacesSearchQueryString = 'select Id, Name, Term_Months__c, Used__c, from Space2__c where RecordTypeId = :SpaceRecordType and {{condition}}';
            String spacesSearchCountQueryString = 'select count() from Space2__c where RecordTypeId = :SpaceRecordType and {{condition}}';
            String spacesSearchQueryConditionString = '';
            
            mapHoldingSelectedRecords.clear();
            
            if(spa.Term_Months__c != null) {
                spacesSearchQueryConditionString += 'Term_Months__c = ' + '\'' + spa.Term_Months__c + '\'' + ' and ';    
            }
            
            if(spa.Used__c != null) {
                spacesSearchQueryConditionString += 'Used__c = ' + '\'' + spa.Used__c + '\'' + ' and ';    
            }
            
            if(String.isBlank(spacesSearchQueryConditionString)) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Please select the suitable filters to search for pSpaces.'));
                return;
            }
            
            spacesSearchQueryConditionString = spacesSearchQueryConditionString.removeEnd(' and ');
            spacesSearchQueryConditionString = spacesSearchQueryConditionString.trim();
            
            spacesSearchQueryString = spacesSearchQueryString.replace('{{condition}}', spacesSearchQueryConditionString + ' order by Name ASC limit ' + QUERY_LIMIT);
            spacesSearchCountQueryString = spacesSearchCountQueryString.replace('{{condition}}', spacesSearchQueryConditionString);
            
            System.debug('------------------- spacesSearchQueryString: ' + spacesSearchQueryString);
            
            setController = new ApexPages.StandardSetController(Database.getQueryLocator(spacesSearchQueryString));
            setController.setPageSize(PAGE_SIZE);
            noOfRecords = Database.countQuery(spacesSearchCountQueryString);
            totalPages = getTotalPages();
            
            populateWrapperList();
            
        } catch(Exception e) {
            System.debug('------------------- ERROR: ' + e.getStackTraceString());
            System.debug('------------------- ERROR MESSAGE: ' + e.getMessage());
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error while searching for pSpaces.' + e.getMessage()));
            return;
        }
    }

The recordType is "Space".  Thanks in advance.


 
Hi, I am new in Salesforce and now I am learning about lightning components.
I have this code:
<aura:component controller="AcordeonControlador"> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> 
    <aura:attribute name="lstAcc" type="List"/>
    <lightning:accordion>
        <aura:iteration items="{!v.lstAcc}" var="acc">
            <lightning:accordionSection name="{!acc.Name}" label="{!acc.Name}">
                <lightning:icon iconName="standard:account"/>
                <p>Telefono: {!acc.Phone}</p>
                <p>Dirección: {!acc.ShippingStreet}</p>
                <p>Ciudad: {!acc.ShippingCity}</p>
                <p>Estado: {!acc.ShippingState}</p>
                <p>Codigo postal: {!acc.ShippingPostalCode}</p>
                <p>Pais: {!acc.ShippingCountry}</p>
            </lightning:accordionSection>
        </aura:iteration>
    </lightning:accordion>   
</aura:component>
I would like to set the label of the accordionSection as: icon + text.
Is there any way to do this?
Thanks in advance.
 
Hi Friends,
 
In opportunities vendor is a multiselect picklist field. I am creating a Process Builder to create a task if a with subject (“vendor-test please call”) if Vendor is “Vendor test – Contracted” or “Vendor test – Background” and if Vendor is
“Vendor – Contracted” or “Vendor– Background” it should create a task if a with subject (“vendor please call”). It is working fine is we are selecting only one value, but is failing if more than one vendor is selected.
 
 For example: if we select two picklist value Vendor – Contracted and Vendor-Paid
“Vendor – Contracted; Vendor-Paid” , the task is not getting created. Any help will be appreciated.
 
Regards,
Vikas
 
Hi all,

I am working through the Visualforce Mobile trailhead, and in the "Use the Salesforce Lightning Design System to Style Visualforce Pages" module, the first step of the exercise defines this class;
 
<apex:page showHeader="false" standardStylesheets="false" sidebar="false" applyHtmlTag="false" applyBodyTag="false" docType="html-5.0">

  <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>SLDS LatestAccounts Visualforce Page in Salesforce Mobile</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />

      <!-- Import the Design System style sheet -->
      <apex:slds />
    </head>     
    <body>

      <!-- REQUIRED SLDS WRAPPER -->
      <div class="slds-scope">

         <!-- PRIMARY CONTENT WRAPPER -->
         <div class="myapp">

         </div>
         <!-- / PRIMARY CONTENT WRAPPER -->

      </div>
      <!-- / REQUIRED SLDS WRAPPER -->

      <!-- JAVASCRIPT -->
      <!-- / JAVASCRIPT -->
    </body>
  </html>
</apex:page>
When the class is saved, an error is produced:
"The API version you've specified is lower than the minimum version of 39 for the apex:slds object"
This happens in both the developer console and mavensmate/sublime. 

Is there any way to fix this so I can continue the module?

Thanks
Hi All,

I have reached the last unit of the https://trailhead.salesforce.com/modules/sfdx_app_dev/units/sfdx_app_dev_setup_dx module yesterday and thought of continuing today. But unfortunately, force:org:open -u TempUnmanaged command is throwing an error. This command was working properly yesterday.

Please guide me.
 
D:\Nayana D Drive\Nayana\Trailhead Stuff\SFDX Trail\MutualFundExplorer>sfdx forc
	e:org:list --verbose
	=== Orgs
		 ALIAS   USERNAME              ORG ID              CONNECTED STATUS
	───  ──────  ────────────────────  ──────────────────  ────────────────
	(D)  DevHub  devhub@trailhead.com  00D7F000002ZgNYUA0  Connected


	  ALIAS          SCRATCH ORG NAME  USERNAME                            ORG ID
			   STATUS  DEV HUB             CREATED DATE                  INSTANCE UR
	L                                              EXPIRATION DATE
	  ─────────────  ────────────────  ──────────────────────────────────  ─────────
	─────────  ──────  ──────────────────  ────────────────────────────  ───────────
	─────────────────────────────────────────────  ───────────────
					 Demo Company      test-jm9x2pkl2h0s@demo_company.net  00D0l0000
	000XA6EAM  Active  00D7F000002ZgNYUA0  2017-10-13T10:52:15.000+0000  https://jav
	a-data-5232-dev-ed.cs58.my.salesforce.com      2017-10-20
	  GeoAppScratch  Demo Company      test-ty4lfw6cokgv@demo_company.net  00D0l0000
	000XHrEAM  Active  00D7F000002ZgNYUA0  2017-10-16T11:24:11.000+0000  https://pag
	e-data-2087-dev-ed.cs58.my.salesforce.com      2017-10-23
	  GeoTestOrg     Demo Company      test-plhfjartzy94@demo_company.net  00D0l0000
	000XIFEA2  Active  00D7F000002ZgNYUA0  2017-10-16T12:59:28.000+0000  https://cus
	tomer-ruby-9006-dev-ed.cs58.my.salesforce.com  2017-10-23
	  TempUnmanaged  Demo Company      test-eflatimr9jvm@demo_company.net  00D0l0000
	000XHqEAM  Active  00D7F000002ZgNYUA0  2017-10-16T13:28:46.000+0000  https://dat
	a-force-9071-dev-ed.cs58.my.salesforce.com     2017-10-23



	D:\Nayana D Drive\Nayana\Trailhead Stuff\SFDX Trail\MutualFundExplorer>sfdx forc
	e:org:open -u TempUnmanaged
	ERROR:  Failed to decipher auth data. reason: Unsupported state or unable to aut
	henticate data.

	D:\Nayana D Drive\Nayana\Trailhead Stuff\SFDX Trail\MutualFundExplorer>sfdx forc
	e:org:open -u TempUnmanaged --json
	{"message":"Failed to decipher auth data. reason: Unsupported state or unable to
	 authenticate data.","status":1,"stack":"authDecryptFailed: Failed to decipher a
	uth data. reason: Unsupported state or unable to authenticate data.\n    at ALME
	rror (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_modules\\salesforce
	-alm\\dist\\lib\\almError.js:35:19)\n    at Crypto.decrypt (C:\\Users\\Nayana\\A
	ppData\\Local\\sfdx\\plugins\\node_modules\\salesforce-alm\\dist\\lib\\crypto.js
	:157:19)\n    at Object.keys.forEach (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\p
	lugins\\node_modules\\salesforce-alm\\dist\\lib\\configValidator.js:61:36)\n
	at Array.forEach (<anonymous>)\n    at crypto.init.then (C:\\Users\\Nayana\\AppD
	ata\\Local\\sfdx\\plugins\\node_modules\\salesforce-alm\\dist\\lib\\configValida
	tor.js:51:37)\n    at tryCatcher (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugi
	ns\\node_modules\\bluebird\\js\\release\\util.js:16:23)\n    at Promise._settleP
	romiseFromHandler (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_module
	s\\bluebird\\js\\release\\promise.js:510:31)\n    at Promise._settlePromise (C:\
	\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_modules\\bluebird\\js\\relea
	se\\promise.js:567:18)\n    at Promise._settlePromise0 (C:\\Users\\Nayana\\AppDa
	ta\\Local\\sfdx\\plugins\\node_modules\\bluebird\\js\\release\\promise.js:612:10
	)\n    at Promise._settlePromises (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plug
	ins\\node_modules\\bluebird\\js\\release\\promise.js:691:18)\n    at Async._drai
	nQueue (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_modules\\bluebird
	\\js\\release\\async.js:138:16)\n    at Async._drainQueues (C:\\Users\\Nayana\\A
	ppData\\Local\\sfdx\\plugins\\node_modules\\bluebird\\js\\release\\async.js:148:
	10)\n    at Immediate.Async.drainQueues (C:\\Users\\Nayana\\AppData\\Local\\sfdx
	\\plugins\\node_modules\\bluebird\\js\\release\\async.js:17:14)\n    at runCallb
	ack (timers.js:781:20)\n    at tryOnImmediate (timers.js:743:5)\n    at processI
	mmediate [as _immediateCallback] (timers.js:714:5)","name":"authDecryptFailed","
	warnings":[]}

I followed https://salesforce.stackexchange.com/questions/188735/im-unable-to-use-sfdx-forceorgopen-command-after-authorizing-an-org-via-the-s link's answer, still no luck.
 

 
DateTime dtOrigin = DateTime.newInstance(2017, 03, 12, 2, 3, 0);
DateTime startDateOfSchedule = dtOrigin;
String timeVal = ' 02:03';
Date startDate = date.newinstance(startDateOfSchedule.year(), startDateOfSchedule.month(), startDateOfSchedule.day());

system.debug('=dtOrigin=='+dtOrigin);
system.debug('=startDateOfSchedule=='+startDateOfSchedule);
system.debug('=timeVal=='+timeVal);
system.debug('=startDate=='+startDate);
system.debug('=Formatted startDate=='+startDate.format());
DateTime dtVal = DateTime.parse(startDate.format()+''+timeVal);
system.debug('=dtVal=='+dtVal);

I have a problem in VF page for particular date time in apex controller. Above is snippet which I ran in dev console and got same error like appeared in VF.
In the above code, I am getting 'Invalid date/time: 12/03/2017 02:03'

If I change DateTime dtOrigin = DateTime.newInstance(2017, 03, 12, 2, 3, 0); to DateTime dtOrigin = DateTime.newInstance(2017, 03, 13, 2, 3, 0);, I won't get error of invalid datetime while parsing DT and assining into dtVal variable. I wonder, why this behaviour only for this specific date and that too for 2hours:some minutes.  

For other date and time combo, there is no error. I find hard time in understanding this.

Please help.
Hi All,

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Delete failed. First exception on row 0 with id 0032800000VuJdTAAV; first error: DELETE_FAILED, Your attempt to delete Sam the ninja could not be completed because it is associated with the following adventure packages.: null, null : []

I am stuck with this error from long time.

I checked with debug logs when challenge tries to test our work. It is :
 
Execute Anonymous: Contact sam = new Contact(firstname='Sam', lastname='the ninja');
Execute Anonymous: insert sam;
Execute Anonymous: Opportunity opp = new Opportunity(name='Make Kite to Fly', stagename='New', closedate=date.today());
Execute Anonymous: insert opp;
Execute Anonymous: // insert product
Execute Anonymous: Product2 product = new Product2(name='Butterfly Net', isActive=true);
Execute Anonymous: insert product;
Execute Anonymous: // insert the pricebookentry
Execute Anonymous: Pricebook2 stdPrice = [Select id from Pricebook2 where isStandard=true limit 1];
Execute Anonymous: PricebookEntry pbe = new PricebookEntry( IsActive = true, Product2Id = product.id, UnitPrice = 2.00, Pricebook2Id = stdPrice.Id);
Execute Anonymous: insert pbe;
Execute Anonymous: // create the opp line item
Execute Anonymous: OpportunityLineItem oli1 = new OpportunityLineItem(OpportunityId=opp.Id, UnitPrice=2, quantity=1,pricebookentryid=pbe.Id, servicedate = date.newInstance(2050, 1, 1), explorer__c = sam.id);
Execute Anonymous: OpportunityLineItem oli2 = new OpportunityLineItem(OpportunityId=opp.Id, UnitPrice=2, quantity=1,pricebookentryid=pbe.Id, servicedate = date.newInstance(2010, 1, 1), explorer__c = sam.id);
Execute Anonymous: insert oli1;
Execute Anonymous: insert oli2;
Execute Anonymous: // this will create a fulfillment record
Execute Anonymous: // find the fulfillment -- by AdventurePackageId__c which is the opp line item
Execute Anonymous: Fulfillment__c f1 = [select id, deposit__c from Fulfillment__c where AdventurePackageId__c = :oli1.Id];
Execute Anonymous: Fulfillment__c f2 = [select id, deposit__c from Fulfillment__c where AdventurePackageId__c = :oli2.Id];
Execute Anonymous: // update the fulfillment and set to cancelled
Execute Anonymous: f1.Status__c = 'Cancelled';
Execute Anonymous: update f1;
Execute Anonymous: f2.Status__c = 'Cancelled';
Execute Anonymous: update f2;
Execute Anonymous: // get the fulfillment again to check the values
Execute Anonymous: oli1 = [select id, unitprice from OpportunityLineItem where Id = :oli1.Id];
Execute Anonymous: oli2 = [select id, unitprice from OpportunityLineItem where Id = :oli2.Id];
Execute Anonymous: // make sure the deposit matches the unit price
Execute Anonymous: System.assertEquals(f1.deposit__c, oli1.unitprice); // one way in the future
Execute Anonymous: System.assertNotEquals(f2.deposit__c, oli2.unitprice); // one way in the past
Execute Anonymous: // clean up
Execute Anonymous: delete opp;
Execute Anonymous: delete f1;
Execute Anonymous: delete f2;
Execute Anonymous: delete product;
Execute Anonymous: delete sam;

I tiried the same in anonymous window except the code of deleting records and there is no error. It means challenge is actually passed. But deleting test records causing error :
User-added image


Please help.
 
Hi Developers,

TREKBIN is hiring 2-5 years of experienced salesforce developers.

Interested candidates, please mail your updated resume to nayana.kashigowda@trekbin.com.

Location : Mumbai, Bangalore.
Here is my code below:

<ul id="insideScroller" class="scrollable-menu scrollbar list-group" style="-webkit-overflow-scrolling: touch;" >
<aura:iteration var="sobj" items="{!v.SobjectRecords}">
<!-- Navigation to record detail page works only SF1-->
<li class="list-group-item" id="{!sobj.SId}" onclick="{!c.navigateToRecord}" >
<aura:renderIf isTrue="{!0 lt v.fieldsToDisplayCount}"> {!v.lstFldDisp[0]} : {!sobj.f1}<br/>
</aura:renderIf>
<aura:renderIf isTrue="{!1 lt v.fieldsToDisplayCount}"> {!v.lstFldDisp[1]} : {!sobj.f2}<br/>
</aura:renderIf>
<aura:renderIf isTrue="{!2 lt v.fieldsToDisplayCount}"> {!v.lstFldDisp[2]} : {!sobj.f3}<br/>
</aura:renderIf> </li>
</aura:iteration>
</ul>
I am using bootstrapcss in which I am able to see scrollbar in SF1 and even on the desktop.But when I load the same page in mobile the scrollbar disappears.

Any workarounds over this?
Hi All,

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Delete failed. First exception on row 0 with id 0032800000VuJdTAAV; first error: DELETE_FAILED, Your attempt to delete Sam the ninja could not be completed because it is associated with the following adventure packages.: null, null : []

I am stuck with this error from long time.

I checked with debug logs when challenge tries to test our work. It is :
 
Execute Anonymous: Contact sam = new Contact(firstname='Sam', lastname='the ninja');
Execute Anonymous: insert sam;
Execute Anonymous: Opportunity opp = new Opportunity(name='Make Kite to Fly', stagename='New', closedate=date.today());
Execute Anonymous: insert opp;
Execute Anonymous: // insert product
Execute Anonymous: Product2 product = new Product2(name='Butterfly Net', isActive=true);
Execute Anonymous: insert product;
Execute Anonymous: // insert the pricebookentry
Execute Anonymous: Pricebook2 stdPrice = [Select id from Pricebook2 where isStandard=true limit 1];
Execute Anonymous: PricebookEntry pbe = new PricebookEntry( IsActive = true, Product2Id = product.id, UnitPrice = 2.00, Pricebook2Id = stdPrice.Id);
Execute Anonymous: insert pbe;
Execute Anonymous: // create the opp line item
Execute Anonymous: OpportunityLineItem oli1 = new OpportunityLineItem(OpportunityId=opp.Id, UnitPrice=2, quantity=1,pricebookentryid=pbe.Id, servicedate = date.newInstance(2050, 1, 1), explorer__c = sam.id);
Execute Anonymous: OpportunityLineItem oli2 = new OpportunityLineItem(OpportunityId=opp.Id, UnitPrice=2, quantity=1,pricebookentryid=pbe.Id, servicedate = date.newInstance(2010, 1, 1), explorer__c = sam.id);
Execute Anonymous: insert oli1;
Execute Anonymous: insert oli2;
Execute Anonymous: // this will create a fulfillment record
Execute Anonymous: // find the fulfillment -- by AdventurePackageId__c which is the opp line item
Execute Anonymous: Fulfillment__c f1 = [select id, deposit__c from Fulfillment__c where AdventurePackageId__c = :oli1.Id];
Execute Anonymous: Fulfillment__c f2 = [select id, deposit__c from Fulfillment__c where AdventurePackageId__c = :oli2.Id];
Execute Anonymous: // update the fulfillment and set to cancelled
Execute Anonymous: f1.Status__c = 'Cancelled';
Execute Anonymous: update f1;
Execute Anonymous: f2.Status__c = 'Cancelled';
Execute Anonymous: update f2;
Execute Anonymous: // get the fulfillment again to check the values
Execute Anonymous: oli1 = [select id, unitprice from OpportunityLineItem where Id = :oli1.Id];
Execute Anonymous: oli2 = [select id, unitprice from OpportunityLineItem where Id = :oli2.Id];
Execute Anonymous: // make sure the deposit matches the unit price
Execute Anonymous: System.assertEquals(f1.deposit__c, oli1.unitprice); // one way in the future
Execute Anonymous: System.assertNotEquals(f2.deposit__c, oli2.unitprice); // one way in the past
Execute Anonymous: // clean up
Execute Anonymous: delete opp;
Execute Anonymous: delete f1;
Execute Anonymous: delete f2;
Execute Anonymous: delete product;
Execute Anonymous: delete sam;

I tiried the same in anonymous window except the code of deleting records and there is no error. It means challenge is actually passed. But deleting test records causing error :
User-added image


Please help.
 
Hi Everyone,

I am currently trying to get a test to work for a simple dynamic apex query.

However, I am getting nothing back when running the test.

Could someone please offer some assistance?

Below is my controller
 
public class UserInfo { 
    Public List<User> getUserInfo() {
       List<User> UserInfo=[Select Name,Kolbe_Score__c,Verb__c,Question_1__c,Question_1_Answer__c,Question_2__c,Question_2_Answer__c,Question_3__c,Question_3_Answer__c,Question_4__c,Question_4_Answer__c,Question_5__c,Question_5_Answer__c,Question_6__c,Question_6_Answer__c,User_Bio_Image_ID__c
                                                      From User                                                     
                                                      Where id = :ApexPages.currentPage().getParameters().get('sfdc.userId') ];
                                                    
                                                                                          
        return UserInfo;
  }
}

My Test
@isTest
public class UserInfoTest 
{ 
    public static testMethod void TestMethod1() 
    {
        User U = new User();
        U.Kolbe_Score__c= 'Test';
        insert U;
        
        
        Test.StartTest(); 

        PageReference pageRef = Page.UserInfoVF; 
        pageRef.getParameters().put('id', String.valueOf(U.Id));
        Test.setCurrentPage(pageRef);

        UserInfo testAccPlan = new UserInfo();
  
        //testAccPlan.save(); call all your function here
        Test.StopTest();
        
    }
   
}


My Visualforce Page is called UserInfoVF

Thank you in advance for your help!
<apex:form >
        <apex:pageBlock mode="edit" >
          <apex:pageBlockButtons location="bottom">
            <apex:commandButton value="Save" action="{!SaveMethod}"/>
            <apex:commandButton value="Cancel" action="{!CancelMethod}"/>
          </apex:pageBlockButtons>
          <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
              <apex:outputLabel value="Subject"/>
             <!-- <apex:outputField value="{!contactRecord.Subject__c}"/> --> 
            </apex:pageBlockSectionItem> <br/>
             <apex:pageBlockSectionItem >
              <apex:outputLabel value="Description"/>
             <!-- <apex:outputField value="{!contactRecord.Description}"/>  -->
            </apex:pageBlockSectionItem> <br/>
            <apex:pageBlockSectionItem >
              <apex:outputLabel value="Contact Name"/>
              <apex:inputField value="{!contactRecord.Contact_ReportIssue__c}"/> 
            </apex:pageBlockSectionItem><br/>
             <apex:pageBlockSectionItem >
              <apex:outputLabel value="Email"/>
             <!-- <apex:outputField value="{!contactRecord.Email}"/> --> 
            </apex:pageBlockSectionItem>   
          </apex:pageBlockSection>
        </apex:pageBlock>
      </apex:form>
</apex:page>


// controller
public class reportIssueRaised {
    public set<Contact> contactRecord {get; set;}
    
    public reportIssueRaised()
    {
      contactRecord = new set<Contact>([select id,Subject__c,Contact_ReportIssue__c,Description,Email from Contact]);
    }
    public PageReference CancelMethod() {
        return null;
    }


    public PageReference SaveMethod() {
        return null;
    }

  
}

Hello Masters,

My requirement here is to create a Trigger on Contact which, in case of change of record ownership, populates a field Previously Owned By with name of the previous owner of the record. Please find my code below and reflect some suggestions to make it work correctly.

trigger PreviousOwnerPopulate on Contact (before update) 
{
Set <ID> PreviousId = new Set<ID>();

for (contact co: trigger.new)
{
for (Contact con: trigger.old)
{

if(co.OwnerID != con.OwnerID)
{
PreviousId.add(con.OwnerID);
}
}

}

map<id,string> mapforPreviousIdname = new map<id,string> ();

for (User u : [select id, name from User where id in:PreviousId])
{
mapforPreviousIdname.put(u.id,u.name);
}

for (contact c : trigger.new)

if (mapforPreviousIdname.size() > 0 )
{
c.Previously_Owned_By__c = mapforPreviousIdname.get(c.OwnerID);
}

Sorry for the really long post, but I am a struggling solo admin trying to make sense of some Apex. I have been getting a lot of errors with various (VERY SIMPLE) process builders, and at Salesforce World Tour Boston, some developers suggested that it may be causing some sort of loop with an existing trigger/Apex in our instance. (I'm getting the "Too many SOQL queries" errors very often, mostly with bulk lead imports). 

We have quite a few managed packages, but only 2 triggers, and 3 Apex classes that were created in-house by a consultant before I started at my company. I have documentation on what exactly it does, and we are willing to remove the functionality that these perform, and just want to get rid of them. 

I tried deactivating the 2 triggers in sandbox and push them to production but got many test failures. So I assumed that I also need to do something with the Apex classes, and found the suggestion to "comment out" the entire thing on another post here in the community.

So my question is how to do that. I tried adding /* at the very beggining and */ at the end, but that gave me the error below. Any help would be GREATLY appreciated. I'm looking forward to learning some of this stuff on my own, but we need to get this done ASAP. 

Best,
Steph

User-added image

And here are the specifics of the Trigger and Apex class code if that is helpful:

EventTrigger 
trigger EventTrigger on Event (after insert, after update) {

    EventTriggerHandler handler = new EventTriggerHandler();

    if (Trigger.isAfter && Trigger.isInsert) {
        handler.afterInsert(Trigger.new);
    } else if (Trigger.isAfter && Trigger.isUpdate) {
        handler.afterUpdate(Trigger.oldMap, Trigger.newMap, Trigger.new);
    }

}

TaskTrigger:
trigger TaskTrigger on Task (after insert, after update) {

    TaskTriggerHandler handler = new TaskTriggerHandler();

    if (Trigger.isAfter && Trigger.isInsert) {
        handler.afterInsert(Trigger.new);
    } else if (Trigger.isAfter && Trigger.isUpdate) {
        handler.afterUpdate(Trigger.oldMap, Trigger.newMap, Trigger.new);
    }

}

ProsepctManagement (Apex Class)
public with sharing class ProspectManagement {

    public static final Set<String> SALES_TASK_TYPES = new Set<String> {
        'Call', 'Email - Sent', 'Email - Opened', 'Email - Clicked', 'Other'
    };

    public static final Set<String> SALES_EVENT_TYPES = new Set<String>{
        'Scheduled Call - Sales', 'Demo', 'Scheduled Call - Cust Success', 'In-person Meeting', 'Other'
    };
    
    private final DateTime NOW;
    private Map<ID, Lead> leads;
    private Map<ID, Contact> contacts;
    
    public ProspectManagement(Set<ID> entityIds) {
        this.leads = this.getLeads(entityIds);
        this.contacts = this.getContacts(entityIds);
        NOW = DateTime.now();
    }
    
    public ProspectManagement(Map<ID, Lead> leads, Map<ID, Contact> contacts) {
        this.leads = leads;
        this.contacts = contacts;
        NOW = DateTime.now();
    }
    
    public Map<ID, Lead> getLeads() {
        return this.leads;
    }
    
    public Map<ID, Contact> getContacts() {
        return this.contacts;
    }
    
    private Map<ID, Lead> getLeads(Set<ID> leadIds) {
        return new Map<ID, Lead>([
            SELECT Id, First_Connect_Date__c, First_Connect_Touch__c, First_Sales_Activity_Date__c,
                Total_Completed_Touches__c
            FROM Lead
            WHERE Id IN :leadIds
        ]);
    }
    
    private Map<ID, Contact> getContacts(Set<ID> contactIds) {
        return new Map<ID, Contact>([
            SELECT Id, First_Connect_Date__c, First_Connect_Touch__c, First_Sales_Activity_Date__c,
                Total_Completed_Touches__c, AccountId
            FROM Contact
            WHERE Id IN :contactIds
        ]);
    }
    
    /**
     * Updates the First_Sales_Activity_Date__c field to now if it wasn't previously set.
     */
    public void updateFirstSalesActivityDateTime(ID entityId) {    
        if (entityId.getSObjectType() == Contact.SObjectType && 
            this.contacts.get(entityId).First_Sales_Activity_Date__c == null) {
            Contact c = this.contacts.get(entityId);
            if (c.First_Sales_Activity_Date__c == null) {
                c.First_Sales_Activity_Date__c = DateTime.now();
            }
        } else if (entityId.getSObjectType() == Lead.SObjectType && 
            this.leads.get(entityId).First_Sales_Activity_Date__c == null) {
            Lead l = leads.get(entityId);
            if (l.First_Sales_Activity_Date__c == null) {
                l.First_Sales_Activity_Date__c = DateTime.now();
            }
        }    
    }
    
    /**
     * Updates leads and contacts, the IDs of which are in entityIds, such that Last_Contacted_Date__c is now.
     * If a Contact has an Account, the Last_Contacted_Date__c field on the Account is also updated.
     * THIS METHOD EXECUTES A DML STATEMENT.
     */
    public void updateLastContactedDate(Set<ID> entityIds) {
        System.debug('Entity IDs: ' + entityIds);
        Set<ID> accountIds = new Set<ID>();
        for (ID entityId: entityIds) {
            if (this.leads.containsKey(entityId)) {
                System.debug('upating lead ' + entityId);
                this.leads.get(entityId).Last_Contacted_Date__c = NOW;
            } else if (this.contacts.containsKey(entityId)) {
                this.contacts.get(entityId).Last_Contacted_Date__c = NOW;
                System.debug('updating contact ' + entityId);
                if (this.contacts.get(entityId).AccountId != null) {
                    accountIds.add(this.contacts.get(entityId).AccountId);
                }
            }
        }
        System.debug('Account IDs: ' + accountIds);
        
        List<Account> accounts = [SELECT Id, Last_Contacted_Date__c FROM Account WHERE Id in :accountIds];
        for (Account a: accounts) {
            a.Last_Contacted_Date__c = NOW;
        }
        
        update accounts;
    }
    
    /**
     * Updates Total_Completed_Touches__c on Leads and Contacts if the ID is contained in entityIds.
     */
    public void updateTotalCompletedTouches(Set<ID> entityIds) {       
        List<AggregateResult> countsPerEntity =([
            SELECT Who.Id entityId, Count(ID)
            FROM Task
            WHERE Cancelled__c = false AND
                Status = 'Completed' AND
                Type IN :SALES_TASK_TYPES AND
                Who.Id IN :entityIds
            GROUP BY Who.Id
        ]);
        countsPerEntity.addAll([
            Select Who.Id entityId, Count(ID)
            FROM Event
            WHERE Cancelled__c = false AND
                StartDateTime <= :now AND
                Type IN :SALES_EVENT_TYPES AND
                Who.Id in :entityIds
            GROUP BY Who.Id
        ]);
        
        Set<ID> entitiesTouched = new Set<ID>();
        for (AggregateResult result: countsPerEntity) {
            ID entityId = (ID) result.get('entityId');
            Integer count = Integer.valueOf(result.get('expr0'));
            if (entityId.getSObjectType() == Contact.SObjectType) {
                Contact c = contacts.get(entityId);
                if (entitiesTouched.contains(entityId)) {
                    c.Total_Completed_Touches__c += count;
                } else {
                    c.Total_Completed_Touches__c = count;
                    entitiesTouched.add(entityId);
                }
            } else if (entityId.getSObjectType() == Lead.SObjectType) {
                Lead l = leads.get(entityId);
                if (entitiesTouched.contains(entityId)) {
                    l.Total_Completed_Touches__c += count;
                } else {
                    l.Total_Completed_Touches__c = count;
                    entitiesTouched.add(entityId);
                }
            }
        }
    }
    
    /**
     * entityIds is a set of IDs of Contacts and Leads associated with a Task where First_Connect__c is set to true.
     */
    public void updateFirstConnectInfo(Set<ID> entityIds) {
        // Count matching tasks and events, and group by the Who.Id
        
        // TODO: Comments from Maggie say we should account for this on a PER ENTITY basis, where we basically have to
        // replay all tasks and events to figure out when the earliest task or event labeled first_connect exists.
        
        // Get eligible leads and contacts associated with the First_Contact__c tasks.
        
        Set<ID> allIds = new Set<ID>();
        // Filter out any entity ids where we've already connected for the first time.
        for (ID leadId: this.leads.keySet()) {
            Lead l = this.leads.get(leadId);
            if (l.First_Connect_Date__c == null && l.First_Connect_Touch__c == null && entityIds.contains(leadId)) {
                allIds.add(leadId);
            }
        }
        for (ID contactId: this.contacts.keySet()) {
            Contact c = this.contacts.get(contactId);
            if (c.First_Connect_Date__c == null & c.First_Connect_Touch__c == null && entityIds.contains(contactId)) {
                allIds.add(contactId);
            }
        }
        
        List<AggregateResult> countPerEntity = [
            SELECT Who.Id entityId, Count(ID)
            FROM Task
            WHERE Cancelled__c = false AND
                Status = 'Completed' AND
                Type IN :SALES_TASK_TYPES AND
                Who.Id IN :allIds
            GROUP BY Who.Id
        ];
        countPerEntity.addAll([
            Select Who.Id entityId, Count(ID)
            FROM Event
            WHERE Cancelled__c = false AND
                StartDateTime <= :now AND
                Type IN :SALES_EVENT_TYPES AND
                Who.Id in :allIds
            GROUP BY Who.Id
        ]);

        // Since there may be two AggregateResults per WhoId, acknowledge when we've SET the value, so next time
        // We increment the value instead.
        Set<ID> entitiesTouched = new Set<ID>();
        for (AggregateResult entityTasks: countPerEntity) {
            ID entityId = (ID) entityTasks.get('entityId');
            Integer count = Integer.valueOf(entityTasks.get('expr0'));
            if (leads.containsKey(entityId)) {
                Lead l = leads.get(entityId);
                if (entitiesTouched.contains(entityId)) {
                    l.First_Connect_Touch__c += count;
                } else {
                    l.First_Connect_Touch__c = count;
                    l.First_Connect_Date__c = now;
                    entitiesTouched.add(entityId);
                }
            } else if (contacts.containsKey(entityId)) {
                Contact c = contacts.get(entityId);
                if (entitiesTouched.contains(entityId)) {
                    c.First_Connect_Touch__c += count;
                } else {
                    c.First_Connect_Touch__c = count;
                    c.First_Connect_Date__c = now;
                    entitiesTouched.add(entityId);
                }
            }
        }
    }
    
    public void updateTotalSalesTouches() {
        // Sum all open and completed tasks of the appropriate types.
        // This includes cancelled touches, per mfitzgerald.
        
        Set<ID> allIds = new Set<ID>();
        // Get eligible leads and contacts associated with the First_Contact__c tasks.
        for (Lead l: this.leads.values()) {
            allIds.add(l.id);
        }
        for(Contact c: this.contacts.values()) {
            allIds.add(c.id);
        }

        List<AggregateResult> tasksPerEntity = [
            SELECT Who.Id entityId, Count(ID)
            FROM Task
            WHERE
                Type IN :SALES_TASK_TYPES AND
                Who.Id IN :allIds
            GROUP BY Who.Id
        ];
        List<AggregateResult> eventsPerEntity = [
            Select Who.Id entityId, Count(ID)
            FROM Event
            WHERE
                Type IN :SALES_EVENT_TYPES AND
                Who.Id in :allIds
            GROUP BY Who.Id
        ];

        // Condense the values of these maps into single values per ID, and stamp those onto the appropriate entity.
        Map<ID, Integer> counts = new Map<ID, Integer>();
        for (AggregateResult agg: tasksPerEntity) {
            counts.put((ID) agg.get('entityId'), Integer.valueOf(agg.get('expr0')));
        }

        for (AggregateResult agg: eventsPerEntity) {
            Integer count = Integer.valueOf(agg.get('expr0'));
            ID entityId = (ID) agg.get('entityId');
            if (counts.containsKey(entityId)) {
                counts.put(entityId, counts.get(entityId) + count);
            } else {
                counts.put(entityId, count);
            }
        }
        
        for (ID leadId: this.leads.keySet()) {
            if (counts.containsKey(leadId)) {
                this.leads.get(leadId).Total_Sales_Touches__c = counts.get(leadId);
            }
        }
        for (ID contactId: this.contacts.keySet()) {
            if (counts.containsKey(contactId)) {
                this.contacts.get(contactId).Total_Sales_Touches__c = counts.get(contactId);
            }
        }
    }
    
    public static Boolean isTaskAllowed(Task t) {
        return SALES_TASK_TYPES.contains(t.Type);
    }
    
    public static Boolean isEventAllowed(Event e) {
        return SALES_EVENT_TYPES.contains(e.Type);
    }
    
    public static Boolean taskJustCompleted(Task oldT, Task newT) {
        return oldT.Status != 'Completed' && newT.Status == 'Completed';
    }
    
    public static Boolean eventJustCompleted(Event oldE, Event newE) {
        return !oldE.Event_Completed__c && newE.Event_Completed__c;
    }

    @future
    public static void handleTasksAndEventsWithNoWhoId(Set<ID> activityIds) {
        List<Task> tasks = [
            SELECT WhoId, Status, Type, Cancelled__c, First_Connect__c
            FROM Task 
            WHERE Id IN :activityIds
        ];
        List<Event> events = [
            SELECT WhoId, Event_Completed__c, Type, Cancelled__c, First_Connect__c
            FROM Event
            WHERE Id IN :activityIds
        ];
        
        if (tasks.size() > 0) {
            TaskTriggerHandler taskHandler = new TaskTriggerHandler(true);
            taskHandler.afterInsert(tasks);       
        }
        
        if (events.size() > 0) {
            EventTriggerHandler eventHandler = new EventTriggerHandler(true);
            eventHandler.afterInsert(events);
        }
    }
}
EventTriggerHandler (Apex Class)
public with sharing class EventTriggerHandler {

    private ProspectManagement prospectManager;
    private Boolean isFutureContext = false;
    
    public EventTriggerHandler() {
    
    }
    
    public EventTriggerHandler(Boolean isFuture) {
        this.isFutureContext = isFuture;
    }
    
    public void afterInsert(List<Event> newEvents) {
        Set<ID> allIds = new Set<ID>();
        List<Event> validEvents = new List<Event>();
        Set<ID> eventsWithoutTargets = new Set<ID>();
        for (Event e: newEvents) {
            if (!ProspectManagement.isEventAllowed(e)) {
                continue;
            }
            if (e.WhoId == null) {
                eventsWithoutTargets.add(e.Id);
                continue;
            }
            allIds.add(e.WhoId);
            validEvents.add(e);
        }

        this.prospectManager = new ProspectManagement(allIds);
        
        this.prospectManager.updateTotalSalesTouches();
        this.updateFirstConnectInfo(validEvents);
        this.updateFirstSalesActivityDateTimeOnInsert(validEvents);
        this.updateTotalCompletedTouchesOnInsert(validEvents);
        this.updateLastContactedDateOnInsert(validEvents);
        
        update this.prospectManager.getLeads().values();
        update this.prospectManager.getContacts().values();
        
        if (!this.isFutureContext && eventsWithoutTargets.size() > 0) {
            ProspectManagement.handleTasksAndEventsWithNoWhoId(eventsWithoutTargets);
        }
    }

    public void afterUpdate(Map<ID, Event> oldMap, Map<ID, Event> newMap, List<Event> newEvents) {
        Set<ID> allIds = new Set<ID>();
        List<Event> validEvents = new List<Event>();
        Map<ID, Event> oldValidEvents = new Map<ID, Event>();
        Map<ID, Event> newValidEvents = new Map<ID, Event>();
        for (Event e: newEvents) {
            if (e.WhoId == null || !ProspectManagement.isEventAllowed(e)) {
                continue;
            }
            allIds.add(e.WhoId);
            validEvents.add(e);
            oldValidEvents.put(e.Id, oldMap.get(e.Id));
            newValidEvents.put(e.Id, newMap.get(e.Id));
        }

        this.prospectManager = new ProspectManagement(allIds);
        this.updateFirstConnectInfo(validEvents);
        this.updateFirstSalesActivityDateTimeOnUpdate(oldValidEvents, newValidEvents);
        this.updateTotalCompletedTouchesOnUpdate(oldValidEvents, newValidEvents);
        this.updateLastContactedDateOnUpdate(oldValidEvents, newValidEvents);
        
        update this.prospectManager.getLeads().values();
        update this.prospectManager.getContacts().values();
    }
    
    /**
     * When a Task or Event is updated to have “First Connect?” = True (manually set by Sales Rep when logging calls
     * and emails), find the Lead or Contact referenced in the “Name” (Who) field, and set the following fields on 
     * that Lead or Contact record only if they are currently blank (we’re looking at FIRST time this happens):
     *     First Connect Touch Number = Get all completed activities associated to the Lead/Contact, ordered by due 
     *         date or event start date, and count the number of activities before and including the first activity 
     *         where Connect = true
     *     First Connect DateTime = Set NOW
     */
    private void updateFirstConnectInfo(List<Event> events) {
        Set<ID> allIds = new Set<ID>();
        Set<ID> updatedEntities = new Set<ID>();
        Set<ID> firstConnectTaskEntities = new Set<ID>();

        // Accumulate the entities associated with First_Contact__c tasks.
        for (Event e: events) {
            if (e.First_Connect__c) {
                firstConnectTaskEntities.add(e.WhoId);
            }
        }
        
        this.prospectManager.updateFirstConnectInfo(firstConnectTaskEntities);
    }
    
    
    /**
     * When a Task is updated to Status = Completed OR an Event startdate time is in the past and Cancelled = false,
     * find the Lead or Contact referenced in the “Name” (Who) field, and if the First Sales Activity Datetime field 
     * is blank, set NOW
     */
    private void updateFirstSalesActivityDateTimeOnInsert(List<Event> events) {
        for (Event e: events) {
            if (e.Event_Completed__c && !e.Cancelled__c) {
                this.prospectManager.updateFirstSalesActivityDateTime(e.WhoId);
            }
        }
    }
    
    /**
     * When a Task is updated to Status = Completed OR an Event startdate time is in the past and Cancelled = false,
     * find the Lead or Contact referenced in the “Name” (Who) field, and if the First Sales Activity Datetime field 
     * is blank, set NOW.
     */
    private void updateFirstSalesActivityDateTimeOnUpdate(Map<ID, Event> oldEvents, Map<ID, Event> newEvents) {
        for (ID eventId: newEvents.keySet()) {
            Event e = newEvents.get(eventId);
            if (ProspectManagement.eventJustCompleted(oldEvents.get(eventId), e)) {
                this.prospectManager.updateFirstSalesActivityDateTime(e.WhoId);    
            }
        }
    }

    /**
     * When a Task is updated to Status = Completed OR an Event startdate time is in the past and Cancelled = false,
     * find the Lead or Contact referenced in the “Name” (Who) field,
     * count all related activities that are “completed” (ignore open tasks and future events), and stamp the number in 
     * this field.
     */    
    private void updateTotalCompletedTouchesOnInsert(List<Event> newEvents) {
        Set<ID> entityIds = new Set<ID>();
        for (Event e: newEvents) {
            if (e.Event_Completed__c && !e.Cancelled__c) {
                entityIds.add(e.WhoId);
            }
        }
        this.prospectManager.updateTotalCompletedTouches(entityIds);
    }

    /**
     * When a Task is updated to Status = Completed OR an Event startdate time is in the past and Cancelled = false,
     * find the Lead or Contact referenced in the “Name” (Who) field,
     * count all related activities that are “completed” (ignore open tasks and future events), and stamp the number in 
     * this field.
     */
    private void updateTotalCompletedTouchesOnUpdate(Map<ID, Event> oldEvents, Map<ID, Event> newEvents) {
        Set<ID> entityIds = new Set<ID>();
        for (ID eventId: oldEvents.keySet()) {
            Event e = newEvents.get(eventId);
            if (ProspectManagement.eventJustCompleted(oldEvents.get(eventId), e)) {
                entityIds.add(newEvents.get(eventId).WhoId);
            }
        }
        this.prospectManager.updateTotalCompletedTouches(entityIds);
    }
    
    private void updateLastContactedDateOnInsert(List<Event> newEvents) {
        Set<ID> entityIds = new Set<ID>();
        for (Event e: newEvents) {
            if (e.Event_Completed__c && !e.Cancelled__c) {
                entityIds.add(e.WhoId);
            }
        }
        this.prospectManager.updateLastContactedDate(entityIds);
    }

    /**
     * When an activity is updated to Status = Completed OR an Event startdate time is in the past and
     * Cancelled = false, find the Lead or Contact referenced in the “Name” (Who) field, and update Last Reach Out Date to NOW
     * Also find the Account associated, and update Last Contacted Date to NOW
     */
    private void updateLastContactedDateOnUpdate(Map<ID, Event> oldEvents, Map<ID, Event> newEvents) {        
        Set<ID> entityIds = new Set<ID>();
        for (ID eventId: oldEvents.keySet()) {
            Event e = newEvents.get(eventId);
            if (ProspectManagement.eventJustCompleted(oldEvents.get(eventId), e)) {
                entityIds.add(e.WhoId);
            }
        }
        this.prospectManager.updateLastContactedDate(entityIds);   
    }       
}

TaskTriggerHandler (Apex Class) - Very similar to the EventTriggerHandler, but my post is already too long so I can't add it! 

 
I have the following class which fails to get code coverage on lines in bold. I have searched through the forums and can't determine how to get those particular lines covered. 

public without sharing class projectWizardController {

Project__c project;

   public Project__c getProject() {
      if(project == null) project = new Project__c();
      project.Plan__c = ApexPages.currentPage().getParameters().get('planId');
      project.Status__c = 'New';
      return project;
   }    
   
   public PageReference step1() {      
      return Page.new_project_p1;
   }
   
   public PageReference step2() {      
      return Page.new_project_p2;
   }
   
   public PageReference step3() {      
      return Page.new_project_p3;
   }
             
   public PageReference submit() {

      try {     
          //if(project.get('Id') == null) 
          project.Status__c = 'Submitted';
          project.Submitted__c = Date.Today();
          insert project;
          PageReference projectPage = new PageReference('/apex/manage_project?id=' + project.id + '&planId='+          ApexPages.currentPage().getParameters().get('planId'));
          projectPage.setRedirect(true);         
          return projectPage;

    
        }
      catch (Exception e) {apexpages.addmessages(e);}return null;

     }         
}

The test class is below.
@isTest
public class projectWizardControllerTest {
  private static testmethod void testSubmittedProject() {
 
    projectWizardController controller = new projectWizardController(); 

    //ARRANGE    
    Plan__c plan = new Plan__c();insert plan;
    Project__c project = controller.getProject();
    project.Plan__c = plan.id;
    project.Status__c = 'Submitted';
    insert project;
    
    //ACT
    Test.startTest();
        controller.step1();
        controller.step2();
        controller.step3();                
        controller.submit();           
        PageReference pageRef = Page.manage_project;
        Test.setCurrentPage(pageRef);
        ApexPages.currentPage().getParameters().put('planid',plan.id);
        ApexPages.currentPage().getParameters().put('id',project.id);
        ApexPages.currentPage().setRedirect(true);        
    Test.stopTest();        
    //ASSERT
    System.assertEquals(project.Status__c, 'Submitted');         
}
}

Hello Community,

My requirement is to display a field Provided_Cash_Amount__c if another field Cash_Provided__c only if it is populated as  'Yes'. I believe I can do it using Rendered, which I tried but couldn't get to work. Please look at the code below:

Visualforce Page:

<apex:page standardController="Response_Action_Plan__c" extensions="RapSaver"  tabStyle="Response_Action_Plan__c">
<apex:form >
<apex:pageBlock >
<apex:sectionHeader title="New Response Action Plan" />
<apex:pageBlockSection title="Information" collapsible="False" columns="1">

<apex:inputField value="{!RAP.name}"/>
<apex:inputField value="{!RAP.Disaster__c}"/>
<apex:inputField value="{!RAP.Causalities_Attended__c}"/> 
<apex:inputField value="{!RAP.Staff_Allotted_Offshore__c}"/>
<apex:inputField value="{!RAP.Staff_Onsite__c}"/>
<apex:inputField value="{!RAP.Onsite_Staff_Count__c}"/>
<apex:inputField value="{!RAP.Blankets_Provided__c}"/>
<apex:inputField value="{!RAP.Number_of_Blankets_Provided__c}"/>
<apex:inputField value="{!RAP.Cash_Provided__c}"/> 
<apex:inputField value="{!RAP.Provided_Cash_Amount__c}" rendered="{!IF(RAP.Cash_Provided__c = 'Yes', true, false)}"/>


</apex:pageBlockSection>
<apex:pageblockbuttons location="Bottom" >
<apex:commandbutton value="Save RAP" action="{!RapSaver}"/>
</apex:pageblockbuttons>
</apex:pageBlock>
</apex:form>
</apex:page>

Extension Class:

Public class RapSaver
{
Public Response_Action_Plan__c RAP{get;set;}
Public ApexPages.StandardController Stcl{get;set;}

Public RapSaver(ApexPages.StandardController str)  
{
Stcl = str;
}

Public RapSaver()                           
{
RAP = new Response_Action_Plan__c();
}

Public PageReference RapSaver()
{
insert RAP;

PageReference pg = new PageReference ('/a07?fcf=00B7F000009BsJx');
pg.SetRedirect(true);

return pg;

}

}


 

Hi All,

Im getting an error like Expecting '}' but was: 'trigger'. Can you help me with this one? Thanks!

@isTest
public class TestRestrictContactByName {

trigger RestrictContactByName on Contact (before insert) {
//check contacts prior to insert or update for invalid data
    For (Contact c : Trigger.New) {
        if(c.LastName == 'INVALIDNAME') {   //invalidname is invalid
            c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML');
        }

    }

}
}
Hello Developers,

I am writing small method in apex class which will use in lightning component. I am following lightning syntax still I am getting compile error. PFB the code snippet which throwing the error.
 
@AuraEnabled public Contact cont{get;set;} 
​@AuraEnabled
 public static id getDetails(){
     Id aa='sss';
     System.debug('caseObjh.Order:::>'+cont.Order_Num__c);
     return aa;
  }
I have referred below link still don't have any clue on this error.
https://salesforce.stackexchange.com/questions/172265/can-we-access-auraenabled-variables-in-auraenabled-methods?rq=1
 
Can you please help me.  Thanks

Regards,
Sagar
 
Message : Challenge Not yet complete... here's what's wrong: 
Could not find a sharing solution 'Volunteerism Board'.

I made this :

User-added image



User-added image





Maybe.. I think problem is 
" Also, provide edit access to this field on an individual-by-individual basis without modifying profiles. Call this solution "Volunteerism Board". "

How can I do?
Hi All, 

Im trying to do the second challenge in App Customization  but am getting some Super badge am getting the error "Challenge Not yet complete... here's what's wrong:  Couldn’t find the 'Volunteer Shift' relationship field or it is not configured correctly."
Please, anyone, can anyone tell me which relationships should be created between these objects? I have created a master-detail relationship between them. 
User-added image

Also, am not clear with this "Shifts with cascading delete and the option of roll-up summary fields." 

Thank you and any help is appreciated.
Thank you in advance. 
I am working on the App Customization Specialist Superbadge and this one has me baffled. Here is the part I'm stuck on...

Quick Self Sign Up
Maria asked for a quick way for users to sign themselves up for a Shift directly from a Volunteer Shift record. Your solution was an action with the label Sign Me Up. To keep it simple there should be no fields on the pop-up. Instead the action automatically sets the Volunteer to the user clicking the button, changes the status to Confirmed, and assigns the currently viewed Shift as the new record's Volunteer Shift. Once the action is done show the friendly message "Congratulations, you are signed up!".

Based on what I'm reading, they seem to be asking me to create a Quick Action button that creates a new record with the necessary fields set to default values. The problem is that two of the fields that are required are Lookups that I was required to create in the first challenge. One to supply the User Name and another to supply the Volunteer Shift Name. Quick Action default values can't populate Lookup fields, right? I tried creating a flow, but you can't trigger an autolaunched flow from a Quick Action, only Screen Flows. The challenge wants one button click and it's done. Can someone tell me what I'm missing here?
Hello, I am just new to salesforce and cannot figure out why iam getting this error....and trying a lot and lots of searches....
So, this is my controller code...where i am declared List<> variable...

public class OnlineExamController 

    public static String selectedExam{get;set;}
    
    public List<OnlineExam__c> o{get;set;}
    
    public List<Integer> iter{get;set;}
    
    public OnlineExamController(ApexPages.StandardController stdController)
    {
        
    }
    
    public OnlineExamController(){}
    
    
    public  List<SelectOption> examName
    {
        get
        {
            examName=new List<SelectOption>();
            examName.add(new SelectOption('----None---','----None---'));
            examName.add(new SelectOption('DAV_401_EXAM','DAV_401_EXAM'));
            examName.add(new SelectOption('DAV_402_EXAM','DAV_402_EXAM'));
            examName.add(new SelectOption('DAV_403_EXAM','DAV_403_EXAM'));
            examName.add(new SelectOption('DAV_404_EXAM','DAV_404_EXAM'));
            
            return examName;
        }
        set;
    }
    
    public PageReference call()
    {
        system.debug(selectedExam);
        o=[Select Questions__c, A__c, B__c, C__c, D__c, E__c, Answer__c, Multiple__c, ExamName__c From OnlineExam__c];
        system.debug(o);
        iter=new List<Integer>{0,1};
        return null;
    }
}
Ad this one is my vf page code , just showing the part which is causing the error because the whole code is too big...to display...

<apex:page controller="OnlineExamController">
<apex:form>
   .
   .
   .
<div class="slds-form slds-form_stacked" style="display:block;">
            <div class="slds-form-element" style="width:100%; margin-top:5%;">
                <div style="float:left;">
                    <label class="slds-form-element__label" style="font-size:20px; margin-left:20px; text-align:left;">Question No.1</label> 
                </div>
                
                <div style="position:relative;float:left; width:70%; margin-left:10px">
                    <b style="font-size:20px;">
         (--PART--------<apex:repeat value="{!iter}" var="pos">
                            <apex:outputText  value="{!o.[pos].Questions__c}"/>
                        </apex:repeat>--------CAUSING ERROR---------)
                    </b>
                </div>

            .
            .
            .
            .
</apex:form>
<apex:page>

Thanks in advance.
I'm having process builder in my org for autocalculation of some fields. Now I have to replace that process builder with code. So I have written code for that but unable to insert fields after any DML operation.Below is my code for the same. data should automatically inser in field 'Exposure_at_Default__c' from  field Limit__c 
*******
trigger EAD_Calculator on Facility__c (after insert, after update) {
    Facility__c[] facList = new Facility__c[] {};
        
        //if (trigger.isAfter){
            if (trigger.isUpdate || trigger.isInsert){
                for (Facility__c fac: Trigger.new) {
                    Facility__c newFac = new Facility__c(id= fac.Id);
                     if(newFac.Limit__c != null){
                            newFac.Exposure_at_Default__c = newFac.Limit__c;
                         system.debug('Limit__c' +newFac.Limit__c);
                         system.debug('Exposure_at_Default__c' +newFac.Exposure_at_Default__c);
                     facList.add(newFac);
               }
            }
         }
      upsert facList;
    }
  • April 03, 2018
  • Like
  • 0
Suppose i have to build follwoing scenario

Two objects A & B have a master detail relationship, A being the master and B can contain many number of records

But only one record in B can be primary to A, say a Primary Flag field exist on B

When i check the Primary Flag of any new record in B, then the primary flag on old record should disappear 

When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.  

 

That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it.