• Lars Nielsen
  • NEWBIE
  • 95 Points
  • Member since 2015
  • Symphonic Source


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

My first controller, can anyone help creating a test class for this?

public class deliverablesController {
  
  // Constructor
 public deliverablesController(ApexPages.StandardController controller) {
  this.proj = (Professional_Services_Partner__c)controller.getSubject();
  
     this.delivers = [ SELECT 
     d.Name, 
      d.Partner_Package__c, d.Price__c, d.Price_Override__c, 
      Professional_Services_Partner_Contract__c, d.Id, d.QTY__c
      FROM 
      Professional_Services_Partner_Line_Items__c d 
      WHERE 
      d.Professional_Services_Partner_Contract__c = :proj.id ];
 }
 
 
public pagereference insertmethod()
                {
                Professional_Services_Partner_Line_Items__c cc= new Professional_Services_Partner_Line_Items__c();
                cc.Professional_Services_Partner_Contract__c = proj.id;
                insert cc;
                return null;
                }
                    
  public Professional_Services_Partner_Line_Items__c[] getDeliverables() { 
  return this.delivers; 
  
 } 
 
 // Action Method called from page button
 public pagereference saveChanges() { 
  upsert this.delivers;
  pageRef.setRedirect(true); 
return pageRef;
 }
 
 // Action Method called from page link
 public pagereference newDeliverable() { 
  Professional_Services_Partner_Line_Items__c d = new Professional_Services_Partner_Line_Items__c();
  d.Professional_Services_Partner_Contract__c =this.proj.id; 
  delivers.add( d );
  getDeliverables();
  return null;
 } 
 
 public pagereference DeleteAccount()   
{      
// if for any reason we are missing the reference       
if (SelectedAccountId == null) 
{               
return null;      
}           
// find the account record within the collection      
Professional_Services_Partner_Line_Items__c tobeDeleted = null;      
for(Professional_Services_Partner_Line_Items__c a : this.delivers)       
if (a.Id == SelectedAccountId) 
{         
tobeDeleted = a;          
break;       
}            
//if account record found delete it      
if (tobeDeleted != null) 
{       
Delete tobeDeleted;      
}
pageRef.setRedirect(true); 
return pageRef;
}        

  
 // class variables

PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl()); 
 

 Professional_Services_Partner__c proj;
 Professional_Services_Partner_Line_Items__c[] delivers; 
 public string SelectedAccountId { get; set; }
}


Best,
Brian
 

Buddies,

I am in learning mode and novice to SFDC. I encrypted the Name field in contact using Platform Encryption and tested it. After testing it, I removed the encryption but seems the residue is still there. When I query the contact object with Name field in where clause, I am getting the error 'encrypted field 'MailingPostalCode' cannot be filtered in a query call'. I am not able to overcome it. Am I missing something here?

PR
 
Long story short I was testing this a few weeks ago and no matter what date ranges we put in it ALWAYS brought back everything in the recycle bin. 
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_getdeleted.htm?search_text=getdeleted

GetDeletedResult = connection.getDeleted(string sObjectType, dateTime startDate, dateTime EndDate);

 
In all the orgs I have investigated so far (a few hundred) it all comes down to the Pocess Builder from what I can see. It is almost like the process builder is not catching the CPU limit and then the moment it hits a managed package it just throws the exception. 

I am seeing people doing a lot of dangerous recursive stuff in the process builder that would normally never fly if you did in Apex but somehow it works and then the next thing down the line pays the price. Anybody else seen similar issues?
I wrote one SOAP webservice Class and I have created one connected app. I want to write login functionality in SOAP webservice.
I am using connected app for authentication.

I used below login code but it's showing Error: Compile Error: Invalid type: ConnectorConfig. error.

ConnectorConfig config = new ConnectorConfig();
config.setManualLogin(true);
EnterpriseConnection sforceConnection = Connector.newConnection(config);
sforceConnection.setLoginScopeHeader(ORGANIZATIONID, PORTALID);
LoginResult loginResult = sforceConnection.login(username, password);
config.setServiceEndpoint(loginResult.getServerUrl());
sforceConnection.setSessionHeader(loginResult.getSessionId()); 


I have a list of SObjects Ed, each SObject SEH is a detail to a Master SObject Student. Each Master SObject Student has a lookup field to SObject Cohort that may be null.
If it the lookup field is not null I want to record Cohort.Name, indexed by that Student. Also I want the list to be unique as multiple Ed entries may point to the same Student.

This is in a trigger so I want to do one SOQL query to create a map to use inside my main for loop. What I'm thinking is that if I can create a list (say studentList) of the Master Object (Student) Ids, I can do a single map statement that will fill from [Select Id, Cohort__c.Name From Student Where Id in :studentList]. It seems like there should be a simple way to create List<Student> studentList... directly from the list of Ed.

Best I have so far is
        map<Id, Boolean> studentMap = new map<Id, Boolean>();
        List<Id> studentList = new List<Id>();
        for (Ed__c stu : edHists) {
            if (stu.Student__c != NULL) {
                if (studentMap.get(stu.Student__c) == NULL) {
                    studentMap.put(stu.Student__c, TRUE);
                    studentList.add(stu.Student__c);
                }
            }
        }
      
        map<Id, Student> studentCohortMap = new map<Id, Student>([
            Select Id, Student__r.Name
            From Student
            Where Id in :studentList AND Cohort__c != NULL
        ]);

Is there something more efficient and/or simpler that my Friday afternoon brain is just missing?
Do we have an object for SharingObjects on which we can run soql ?

My first controller, can anyone help creating a test class for this?

public class deliverablesController {
  
  // Constructor
 public deliverablesController(ApexPages.StandardController controller) {
  this.proj = (Professional_Services_Partner__c)controller.getSubject();
  
     this.delivers = [ SELECT 
     d.Name, 
      d.Partner_Package__c, d.Price__c, d.Price_Override__c, 
      Professional_Services_Partner_Contract__c, d.Id, d.QTY__c
      FROM 
      Professional_Services_Partner_Line_Items__c d 
      WHERE 
      d.Professional_Services_Partner_Contract__c = :proj.id ];
 }
 
 
public pagereference insertmethod()
                {
                Professional_Services_Partner_Line_Items__c cc= new Professional_Services_Partner_Line_Items__c();
                cc.Professional_Services_Partner_Contract__c = proj.id;
                insert cc;
                return null;
                }
                    
  public Professional_Services_Partner_Line_Items__c[] getDeliverables() { 
  return this.delivers; 
  
 } 
 
 // Action Method called from page button
 public pagereference saveChanges() { 
  upsert this.delivers;
  pageRef.setRedirect(true); 
return pageRef;
 }
 
 // Action Method called from page link
 public pagereference newDeliverable() { 
  Professional_Services_Partner_Line_Items__c d = new Professional_Services_Partner_Line_Items__c();
  d.Professional_Services_Partner_Contract__c =this.proj.id; 
  delivers.add( d );
  getDeliverables();
  return null;
 } 
 
 public pagereference DeleteAccount()   
{      
// if for any reason we are missing the reference       
if (SelectedAccountId == null) 
{               
return null;      
}           
// find the account record within the collection      
Professional_Services_Partner_Line_Items__c tobeDeleted = null;      
for(Professional_Services_Partner_Line_Items__c a : this.delivers)       
if (a.Id == SelectedAccountId) 
{         
tobeDeleted = a;          
break;       
}            
//if account record found delete it      
if (tobeDeleted != null) 
{       
Delete tobeDeleted;      
}
pageRef.setRedirect(true); 
return pageRef;
}        

  
 // class variables

PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl()); 
 

 Professional_Services_Partner__c proj;
 Professional_Services_Partner_Line_Items__c[] delivers; 
 public string SelectedAccountId { get; set; }
}


Best,
Brian
 

I have a trigger on lead convert that creates a record in a managed package app.  When I run my test code, i get the following error: "Methods defined as TestMethod do not support Web service callouts". I have tried the httpmock code and istestrunning.  What am I missing?

Here is my trigger
trigger LeadConvert on Lead (after Insert,after update) {
   String recordTypeName = 'ID Lead Record Type'; // <-- Change this to your record type name
  
  Map<String,Schema.RecordTypeInfo> rtMapByName = Schema.SObjectType.Lead.getRecordTypeInfosByName();
  Schema.RecordTypeInfo rtInfo =  rtMapByName.get(recordTypeName);
  id recordTypeId = rtInfo.getRecordTypeId();
 if(!test.isrunningtest()) {
 For(Lead o : Trigger.New){
 If(o.RecordTypeId == recordTypeId){
 
  // no bulk processing; will only run from the UI
  if (Trigger.new.size() == 1) {

    if (Trigger.old[0].isConverted == false && Trigger.new[0].isConverted == true) {

      // if a new account was created
      if (Trigger.new[0].ConvertedAccountId != null) {

        // update the converted account with some text from the lead
        Account a = [Select a.Id, a.Description From Account a Where a.Id = :Trigger.new[0].ConvertedAccountId];
        a.Description = Trigger.new[0].Name;
        update a;

      }          

      // if a new contact was created
      if (Trigger.new[0].ConvertedContactId != null) {

        // update the converted contact with some text from the lead
        Contact c = [Select c.Id, c.Description, c.Name From Contact c Where c.Id = :Trigger.new[0].ConvertedContactId];
        c.Description = Trigger.new[0].Name;
        update c;
         
If(o.Create_Apttus_Proposal__c == True) {
        // insert a custom object associated with the contact
       
        Apttus_Proposal__Proposal__c obj = new Apttus_Proposal__Proposal__c();
        obj.Apttus_Proposal__Proposal_Name__c = c.Name;
        obj.Apttus_Proposal__Description__c = c.Description;
        obj.Apttus_Proposal__Account__c = Trigger.new[0].ConvertedAccountId;
        obj.Due_to_Funder__c = Date.today().addDays(+60);
        obj.Program__c = Trigger.new[0].Program__c;
        obj.Proposal_Reviewer_list__c = Trigger.new[0].Proposal_Reviewer_list__c;
        obj.Total_Proposal_Value__c = 1;
        obj.Apttus_Proposal__ExpectedStartDate__c = Date.today().addDays(+60);
        obj.Apttus_Proposal__ExpectedEndDate__c = Date.today().addDays(+365);
        obj.Account_Contact__c = Trigger.new[0].ConvertedContactId;
        obj.Lead_Id__c = c.id;
        obj.Proposal_Status__c = 'Awaiting RFP';
        insert obj;
}}{
      }

     

   } }

  }     

}
}
}
Here is my test code:
 
@isTest
public class LeadConvertTest {
   
    static testMethod void insertNewLead() {

        Lead newLead = new Lead();
        newLead.LastName = 'Lee';
        newLead.FirstName = 'James';
       newLead.Company = 'TestTrigger';
       newLead.Program__c = 'Assessment & Standards Development Services';
       newLead.Proposal_Reviewer_list__c = 'Aida Walqui';
       newLead.Create_Apttus_Proposal__c = True;

        insert newLead;
       
     test.startTest();
      Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
      

        Database.LeadConvert lc = new Database.LeadConvert();
       lc.setLeadId(newLead.id);

        
        

       LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
//lc.setConvertedStatus(convertStatus.MasterLabel);
lc.setConvertedStatus('Qualified');


       Database.LeadConvertResult lcr = Database.convertLead(lc);
        
        System.assert(lcr.isSuccess());

      test.stopTest();
    }

}


 
Hi,

 I modified below trigger by adding catch exception to handle exception scenarious for some reasons test class which i wrote earlier is getting falied can you please suggest me what is the mistake in the trigger and test class to get this failed. 

Trigger
trigger lead_territory_lookup on Lead (After Update) 
{
 if(checkRecursive_LeadTerritory.runOnce())
  {
  
 
String gcountry;
String gstate;
Integer gzip;


 for(Lead l :   Trigger.new){
    gstate = l.State;
    gcountry = l.Country;
     if ( l.postalcode != null)
     { 
      gzip = Integer.valueof(l.postalcode); 
     } 
  }
 
Territory_Lookup__c  TL;

 if ( gcountry  != null )
 {
 Try
 {
if ( trigger.isInsert || trigger.isupdate )
 {

 if ( gcountry != null && gstate != null && gzip != null  )
{
   TL = [SELECT id,Country__c,State__c,Zip_Start__c,Zip_End__c
                          FROM Territory_Lookup__c
                          WHERE
                          Country__c = :gcountry and
                          State__c = :gstate and
                          Zip_Start__c <= :gzip and Zip_End__c >= :gzip limit 1];
  system.debug('Country & State & Zip');
}

else if ( gcountry != null && gstate != null )
{
 TL = [SELECT id,Country__c,State__c,Zip_Start__c,Zip_End__c
                          FROM Territory_Lookup__c
                          WHERE
                          Country__c = :gcountry and
                          State__c = :gstate limit 1];
  system.debug('Country & State');
}
    
else if ( gcountry != null && gzip != null)
{
   TL = [SELECT id,Country__c,State__c,Zip_Start__c,Zip_End__c
                          FROM Territory_Lookup__c
                          WHERE
                          Country__c = :gcountry and
                          Zip_Start__c <= :gzip and Zip_End__c >= :gzip limit 1];

  system.debug('Country & Zip');
}   

else if ( gcountry != null )
{
   TL = [SELECT id,Country__c,State__c,Zip_Start__c,Zip_End__c
                          FROM Territory_Lookup__c
                          WHERE
                          Country__c = :gcountry limit 1];

      system.debug('Country');

}
else
{
   TL = [SELECT id,Country__c,State__c,Zip_Start__c,Zip_End__c
                          FROM Territory_Lookup__c
                          WHERE
                          Country__c = :gcountry limit 1];

      system.debug('Country');

}

system.debug('ID Name:' + TL.ID);
system.debug('Country Name:' + TL.Country__c);
system.debug('State Name:' + TL.State__c);
system.debug('Zip Start:' + TL.Zip_Start__c);
system.debug('Zip End:' + TL.Zip_End__c);
 

  List<Lead> leds = new List<Lead>();
   
  for(Lead uld : Trigger.new){                              
   Lead  uleds = new Lead( Id = uld.id,Territory_Lookup__c = TL.ID);
   leds.add(uleds);
  }  
    
   update leds;
    
}   
      
 }


catch (Exception e) {

 
 
List<Lead> leds = new List<Lead>();

if ( gcountry != null && gstate != null )
{
 TL = [SELECT id,Country__c,State__c,Zip_Start__c,Zip_End__c
                          FROM Territory_Lookup__c
                          WHERE
                          Country__c = :gcountry and
                          State__c = :gstate limit 1];
  system.debug('Country & State');
  

}
 
else
{
  TL = null;
}

  for(Lead uld : Trigger.new){                              
   Lead  uleds = new Lead( Id = uld.id,Territory_Lookup__c = TL.ID);
   leds.add(uleds);
  }  
    
   update leds;

  
  
}  
} 
}
}

Test Class
@isTest
private class lead_territory_lookup_Test {

        static testMethod void protectFields(){
     
                test.startTest();
               
                List<Lead> lstLead =   new List<Lead>{
                          new Lead(Company = 'JohnMiller', LastName = 'Mike', Status = 'Open',
                                   state='Karnataka',country='India',postalcode='5',LeadSource='Community')

                         };
                 insert lstLead;
                 
                List<Territory_Lookup__c> lstTerritory =   new List<Territory_Lookup__c>{ 
                     new Territory_Lookup__c(Country__c = 'India',State__c ='Goa', Zip_End__c = 50, Zip_Start__c = 51)
                     };
                     
                 insert lstTerritory;     
                 
          
                                         

                lstLead[0].LastName = 'Mike';
                lstLead[0].Territory_Lookup__c = lstTerritory[0].id;
                

                update lstLead;
               

                test.stopTest();
        }
}

Thanks
Sudhir
I opened a case with support and they sent me here?  Is someone monitoring this forum who does this for end users?

Thanks.

Bryan Hunt
  • January 25, 2016
  • Like
  • 0
I want to delete Custom Tab from a released/managed package in salesforce developer edition. Please help on this.

Thanks in advance.

Hi Community,

I am new to Salesforce and using APEX.  I am completely self-taught too.  With that said, I am trying to learn triggers and cannot find an exact example of how to achieve what I am working on.  My problem is that when a Contact updates their information through my Visualforce page, Salesforce will overwright fields with the new data they inputted - which is great, except for the 'Description' field.  I want the new 'Description' to append to whatever they previously had written in that field.  Can anyone help me?

The pseudo code would be something like:

trigger UpdateDescription on Contact (before update) {
          Contact.Description = Contact.OldDescription + " " + Contact.NewDescription;

}

Thank you in advance for your help!

Hi All,

Any One  please help me to code coverge because i got only 43% coverage

ApexTrigger :-
trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Lead_Campaign__c tm;//Assinging Custom setting To the variable tm
    tm=Lead_Campaign__c.getorgdefaults();
    String Template=tm.Email_Template_ID__c;
    Decimal Days=tm.Threshold_Days__c;
     
    list <CampaignMember> theCampaignMembers = new list<CampaignMember>();
    for(CampaignMember campMem : Trigger.new){//
    if(test.isRunningTest()){
        
        Days = 0;
    }
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
            theCampaignMembers.add(campMem);
         
            }
    // List containing Campaign Member records to be inserted  
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Status,Lead_age__c, owner.email from Lead where id IN : LeadIds])
    try
    {

    if(ld.Status!='Qualified'&&ld.Lead_age__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
 
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
      mail.setTargetObjectId(ld.OwnerId);    
      mail.setWhatId(ld.id);
      mails.add(mail);
      Messaging.sendEmail(mails);
  
}
}
 catch (Exception e)
{

  ApexPages.addMessages(e);
  Profile adminProfile = [Select id From Profile Where Name='System Administrator' Limit 1];

     Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
     List<String> toAddresses = new List<String>();
     toAddresses.add(adminProfile.id);
     mail.setToAddresses(toAddresses);
     mail.setSenderDisplayName('Apex error message');
     mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
     mail.setPlainTextBody(e.getMessage());
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
  
}
}


Test Class -:

@isTest(SeeAllData = true)
public class sendNotificationTrigger
{
static testMethod void sendNotificationTrigger ()
{
     Test.startTest();      //Creates Contact to be linked to Campaign Member
Campaign cp =  [SELECT Id FROM Campaign LIMIT 1];
       //Creates a new campaign memeber, associaites it with 1 campaign
 Lead t1 = new Lead(Company= 'TestLead', LastName= 'TestL', Email = 'none@test.com',Status = 'Open' );
 insert t1;
 CampaignMember newMember = new CampaignMember (LeadId = t1.id, status='Sent', campaignid = cp.id);
 insert newMember;
 system.assertequals(t1.status,'Open')  ;

  
 
   
 Test.stopTest();
 }


Thanks,
Raj.
Buddies,

I am in learning mode and novice to SFDC. I encrypted the Name field in contact using Platform Encryption and tested it. After testing it, I removed the encryption but seems the residue is still there. When I query the contact object with Name field in where clause, I am getting the error 'encrypted field 'MailingPostalCode' cannot be filtered in a query call'. I am not able to overcome it. Am I missing something here?

PR
 
Hi All,

  I have requirement for Inactive account  if there is no activity like(task,event) assigned for last 30 days for that account.Anyone help on this scenario.Give some sample code.How to implement.

Thanks,
vicky
 
Prior to Winter '16 the lead conversion page would properly display error messages that contain HTML if you called sObject.addError() with the escape parameter set to false, but this was broken with the new release.  This breaks some of the functionality of one of our products and impacts quite a few of our customers.

I don't see this as an existing known issue, could some look into this and create a known issue and possible ETA for a fix?
  • October 15, 2015
  • Like
  • 1
Prior to Winter '16 the lead conversion page would properly display error messages that contain HTML if you called sObject.addError() with the escape parameter set to false, but this was broken with the new release.  This breaks some of the functionality of one of our products and impacts quite a few of our customers.

I don't see this as an existing known issue, could some look into this and create a known issue and possible ETA for a fix?
  • October 15, 2015
  • Like
  • 1