• sfck
  • NEWBIE
  • 375 Points
  • Member since 2011

  • Chatter
    Feed
  • 14
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 74
    Replies

So I have this trigger, which makes a call to a Apex class, which makes a SOQL whenver the function/method is called

 

Apex:

		for(Integer x = 0; x < Trigger.new.size(); x++){
....
			if (ZipCode != NULL && PriBoro == NULL){
				ZipCodeList fillPriBoro = new ZipCodeList();
				fillPriBoro.ZipCode = ZipCode;
				trigger.new[x].Primary_Borough__c = fillPriBoro.getBorough();
			}	
....

 In the ZipCodeList:

public with sharing class ZipCodeList {
...
public ZipCodeList(){}

	public string getBorough (){
		if (ZipCode.length()>=5)
			ZipCode = ZipCode.substring(0, 5);
		
		Borough = [SELECT Borough__c FROM Address__c WHERE Zip_Code__c = :ZipCode];
		
		if (Borough.size()>=1){
			return Borough[0].Borough__c;
		}else {
			return NULL;
		}
	}
	
...
}

 So i read somewhere that in my case everytime that for loop is called from the trigger, it makes soql query call.

 

How would i approach this when each time i call this apex class, I alway need it to return that one Borough data.

 

I have the following trigger that needs to have a test method before I can deploy it and would like any advice on how to do this.

 

 

trigger createworkorder on Opportunity (after update)
{
if(trigger.new[0].StageName=='closed won'&&(trigger.old[0].StageName<>'closed won'))
{
Work_Order__c obj=new Work_Order__c(Opportunity__c=trigger.new[0].id);
insert obj;
case c1=new case(Status='new',Subject='Create Product Cases for Work Order',Work_Order__c=obj.id);
insert c1;
}
}

Hi

 

I'm using an extension to display data from the parent record (Site__c) on my VF page, this works correctly when i click on an existing record (Investment__c) in the related list, however, when i add a new Investment__c i get the following error:

 

System.QueryException: List has no rows for assignment to SObject

 

I'm guessing this is becausethe Id isn't available at this point ofr the new record. So does anyoneknow how i can get round this?

 

Code excerpt  below, Thanks for any suggestions!

Paul

 

	//get data from Parent Object
        Investment__c inv = (Investment__c)stdController.getRecord();
        
    	inv = [Select ID, Site__r.Address__c, Site__r.Postcode__c, Site__r.Town__c from Investment__c
    			where id=:stdController.getRecord().Id limit 1];
    			
    	SiteObj = inv.Site__r;
    //////

 

 

  • March 01, 2012
  • Like
  • 0

Hi,

 

Im writing a tigger on task  .Im trying to update the task related to opportunity but  it showing error like this.

 

Apex trigger Update_completed_activities_in_Opportunity caused an unexpected exception, contact your administrator: Update_completed_activities_in_Opportunity: execution of AfterUpdate caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.Update_completed_activities_in_Opportunity: line 26, column 1


trigger Update_completed_activities_in_Opportunity on Task (after update) {
Opportunity O;

/*
List<Id> oId = new List<Id>();
for(Task T : Trigger.new) {
        oId.add(T.Whatid);
   }
*/

for (Task T : trigger.new)
    {
        O = [select id, 
                    Welcome_Call_Completed__c, 
                    Welcome_Kit_Dispatched__c,
                    Agreement_Amount_Received__c,
                    Construction_Agreement_Received__c,
                    Sale_Agreement_Received__c from Opportunity where id =: T.Whatid];
        
        if(T.Status == 'completed' && T.Subject == 'Welcome Call' && !O.Welcome_Call_Completed__c)
        {
            O.Welcome_Call_Completed__c = true;
        }
        if(T.Status == 'completed' && T.Subject == 'Dispatch Welcome Kit' && !O.Welcome_Kit_Dispatched__c)
        {
            O.Welcome_Kit_Dispatched__c = true;
        }
        if(T.Status == 'completed' && T.Subject == 'Collect Agreement Amount' && O.Agreement_Amount_Received__c == Null)
        {
            O.Agreement_Amount_Received__c = System.today();
        }
        if(T.Status == 'completed' && T.Subject == 'To check physical receipt of Agreement Copies' && !O.Construction_Agreement_Received__c && !O.Sale_Agreement_Received__c)
        {
            O.Construction_Agreement_Received__c = true;
            O.Sale_Agreement_Received__c = true;
        }


    }
update O;
}

 

  O = [select id, 
                    Welcome_Call_Completed__c, 
                    Welcome_Kit_Dispatched__c,
                    Agreement_Amount_Received__c,
                    Construction_Agreement_Received__c,
                    Sale_Agreement_Received__c from Opportunity where id =: T.Whatid];
        

 

I understood it is because im not able to map task id with opportunity.How to map task id with opportunity.Im not so familiar in trigger .any one suggest me a solution for this asap

 

Thanks

 

 

  • February 29, 2012
  • Like
  • 0

Hi,

 

I currently have a small form that a user can input 4 fields for a new entry into the database. Everything works fine when I remove the "Unique" check for dupes on the Email field. But if I have it enabled, it jumps to the auth required screen.

 

As you can see below, the class is very simple and functions properly if a user inputs a new entry that does not exist. How can I check against unique at the insert? Or should I be doing a field validation rule? Not sure which is the best path to take.

 

public class addbrokerclass 
{
	public Broker_Contact__c newBroker { get; set; }
		
	public addbrokerclass() 
	{ 
	newBroker = new Broker_Contact__c();
	}
	
	public PageReference add() {
		insert newBroker;
		return new PageReference('/survey/landing');
                            }
}

 Thanks in advance!

  • February 27, 2012
  • Like
  • 0
Until recently, whenever I would hit ctrl-S, not only would eclipse save my code locally, but it would also save to SFDC. A few days ago, for no reason I can see, it stopped. Now it just saves locally and I have to right-click - force.com - save to server which is a pain as it runs in the foreground, not the background, and it's more typing and clicks.

Anybody experienced such a problem? Solution? thanks.

Hi All,

 

I have created a Task Controller and Visualforce Page so a User can click a button on a custom object and it will create a prepopulated Task.  Meaning the User then just needs to click "Create Task".  This all works fine, however, still being an amature I can't get the TestMethod to work. 

 

If anyone could point me in the right direction I would really appreciate it.

 

public class Custom_Referral_Task_Controller { 
 
    Id idReferralClass = null;
    public Referral__c ReferralCurrent {get;set;}
    public Task tskNew {get;set;}

    public void createTaskRecord() {

        tskNew = new Task();
   
        tskNew.OwnerId = '005E0000000YhNn';
        tskNew.WhoId = '003M0000008jjA5';
        tskNew.WhatId = 'a06M0000002pW2o';
        tskNew.Subject = 'Referral Validation';
        tskNew.ActivityDate = date.today() + 7;
        tskNew.ReminderDateTime = datetime.now() + 7;
        tskNew.Description = 'Test Task'; // Pull concatenated text see above
    }

    public PageReference saveAndProceed() {

       
        //Insert Task
        try {
            insert tskNew;

        } 
        catch(DMLException e) {
            tskNew.addError(e.getMessage());
            return null;
        }

        // Return URL to Referral Object
        PageReference pf = new PageReference('/' + ReferralCurrent.Id);
        pf.setRedirect(true);
        return pf;
    }

}

 

So I tried creating the below TestMethod, however, I get 0% coverage.  I think my issue is I'm not actual testing the controller but I'm not sure where I am going wrong.

 

static testmethod void testCustomReferralTaskController() {

	try
	{
	
    Test.startTest();
    	//Create Referrer
    	VistageTestData data = new VistageTestData();
    	Account[] testAccounts = data.gimmeAccounts(2);
    	Contact testContact = data.gimmeContacts(testAccounts)[0];
    	Contact testContactDetails = [SELECT Id, FirstName, LastName, Staff__c FROM Contact WHERE Id = :testContact.Id];
    	testContactDetails.Staff__c = true;
    	update testContactDetails;
    
	//Create Referral
	VistageTestData data2 = new VistageTestData();
	Account[] testAccounts2 = data2.gimmeAccounts(2);
	Contact testContact2 = data2.gimmeContacts(testAccounts)[0];
	Contact testContactDetails2 = [SELECT Id, FirstName, LastName, Staff__c FROM Contact WHERE Id = :testContact.Id];
	testContactDetails2.Member__c = true;
	update testContactDetails2;    
    
	Referral__c Referral = new Referral__c(
        Referrer__c = testContactDetails.Id,
        Contact_Referral_Name__c = testContactDetails2.Id
		);
        insert Referral;
            
	Task testTask = new Task (
		WhoId = testContactDetails2.Id,
		WhatId = Referral.Id,
		Subject = 'Referral Validation',
		ActivityDate = date.today() + 7,
		ReminderDateTime = datetime.now() + 7,
		Description = 'Please Validate the Referral');
	insert testTask; 
    
   	Task t = [Select Id, whoid from Task where WhatId = :Referral.Id Limit 1];
   	system.assertEquals(t.whoid,testContactDetails2.Id);
   	Test.stopTest();
	
	}
	catch(exception e)
	{
		system.assertequals(e,null);
	}

} 

 

Many thanks in advance for any help or guidance.


Kev

 

hi,

            I have 2 objects  Employee and Department.                         Fields are..................        

 

Employee                                                   department

 

-----------                                                   ---------------

empname:                                              deptname

dept(lookup)                                          no_of_employees

 

No of employees   should be reflected for each insert,update,delete.

 

There are 3 cases in this...

 

1.  If i add employee and department(lookup) in Employee object......No of Employee should be increased...N

2.   if i delete an employee of a particular department...it should less 1 from No of Employee..

3   If i update employee department to another department...it should be reflected on both the departments...ie.-1from           current department...and +1 to the updated department..

 

                                                                          Thank you

Hi ,

 

How to write query for self join and how can i use count to count the realted records for that .

 

 

Thanks

Shailu

  • November 29, 2011
  • Like
  • 0

Is it possible to traverse the configuration objects in APEX script? 

 

I would like run a trigger from the USER object which checks to see if the user appears on any approval configurations before I allow the user record to be made in-active (I don't mean check to see if they have OUTSTANDING approvals but I mean check if they could ever appear on ANY approvals in the future - ie. are they listed in any approval steps). 

 

Does Salesforce expose these objects to developers? I have had a search for these objects but the only ones I can find relating to approvals relate to firing off and managing an approval process on an existing object. 

 

Note: a bit of an APEX newbie alert (been a developer for years but new to APEX and quite new to SF). :smileyhappy:

 

Thanks in advance. 

Hi,

 

I have a class written and when i move the class to production i get an error. Everything seems to work fine on sandBox.

If i remove the block of code it passes the code to production. I have a almost similar piece of code just

below the erroring code. This works fine and gets passed over into production. Any ideas on what could

be the issue?

 

Failure Message: "System.NullPointerException: Attempt to de-reference a null object", Failure Stack Trace: "Class.AppointmentController.refresh: line 252, column 82 Class.Test_Appointment.Testapp: line 29, column 6 External entry point"

 

Here is my code

 

Public Class AppointmentController
{

    public PageReference createApp() {
    
        return page.Appointment;
    }

Public Appointment__c Appointment { get; set; }
public String Error { get; set; }
public String ClientsSearch { get; set; }
public list<CEventTimeSlot> liETimeSlots {get;set;}
public list<CEventTimeSlot> liETimeSlots_form {get;set;}
public list<CTimeSlot> liTimeSlots {get;set;}
public list<CTimeSlot> liTimeSlots_form {get;set;}
public Map<string,CTimeSlot> mapTimeToSlot {get;set;}
public Map<string,CEventTimeSlot> mapETimeToSlot {get;set;}
public List<String> LstString{get;set;}

Public AppointmentController()
{
Appointment = new  Appointment__c();
}
   


/* function called from VF page for updating the startdatetime and endDatetime  and rendering into VF page   */
   public PageReference refresh() {
    try
      {
         liTimeSlots = new list<CTimeSlot>();
         mapTimeToSlot = new Map<string,CTimeSlot>();
         liTimeSlots_form = new list<CTimeSlot>();
         //For adding Events
         liETimeSlots = new list<CEventTimeSlot>();
         mapETimeToSlot = new Map<string,CEventTimeSlot>();
         liETimeSlots_form = new list<CEventTimeSlot>();
          
          
          
         

        
      if (Appointment.Start_Date__c<>null)
      {
        Time pktime;
        Time pkTime1;
        List<Time> LstTime = new List<Time>();
        pktime=time.newInstance(7,0,0,0);
        LstTime.add(pktime);

        for(integer ctr=0; ctr<30;ctr++)
        {
            pktime=pktime.addMinutes(30);
            LstTime.Add(pkTime);
        }
        system.Debug(' Listtime '+LstTime);
        
        system.debug('No of Time Items'+LstTime.size());
        for(integer ctr1=0; ctr1<LstTime.size();ctr1++)
        {       
        
        CTimeSlot newSlot = new CTimeSlot(string.valueof(LstTime[ctr1]));
        liTimeSlots.add(newSlot);
        
        mapTimeToSlot.put(string.valueof(LstTime[ctr1])+ '', newSlot);
        newSlot=null;
        
        CEventTimeSlot newESlot = new CEventTimeSlot(string.valueof(LstTime[ctr1]));
        liETimeSlots.add(newESlot);
        
        mapETimeToSlot.put(string.valueof(LstTime[ctr1])+ '', newESlot);
        newESlot=null;
        }
        
        
		system.debug('liETimeSlots.....'+liETimeSlots);
		system.debug('mapETimeToSlot.....'+mapETimeToSlot);
        String t_startdatetime_str;
        String t_enddatetime_str;
        integer t_syear;
        
        integer t_smonth;
        integer t_day;
        t_syear=Appointment.Start_Date__c.year();
        t_smonth=Appointment.Start_Date__c.month();
        t_day=Appointment.Start_Date__c.day();
        t_startdatetime_str=t_syear+'-'+t_smonth+'-'+t_day+' 00:00:00';
        datetime t_startdatetime;
        datetime t_enddatetime;
        t_startdatetime=datetime.valueof(t_startdatetime_str);
        t_enddatetime=t_startdatetime.addHours(23);
        t_enddatetime=t_enddatetime.addMinutes(59);
        t_enddatetime=t_enddatetime.addSeconds(59);
        
        
        datetime Ls_startdatetime;
        datetime Ls_enddatetime;
        
        //t_startdatetime=Appointment.Start_Date__c.format();
        system.debug('t_startdatetime'+t_startdatetime);
        
        List<Appointment__c> a=[select id, name,Appointment_Type__c,Status__c,StartDateTime__c,EndDateTime__c,Duration__c, ap.Client_First_Name__c,patient__c,subject__c from Appointment__c ap where   
         (
                                  (ap.StartDateTime__c >= :t_startdatetime  AND ap.StartDateTime__c <= :t_enddatetime) OR
                                  (ap.EndDateTime__c >= :t_startdatetime  AND ap.EndDateTime__c <= :t_enddatetime) OR
                                  (ap.StartDateTime__c <= :t_startdatetime   AND ap.EndDateTime__c >= :t_enddatetime)
                               )];
                               
        List<Event> eve=[select id, subject,StartDateTime,EndDateTime from event eve where   
         (
                                  (eve.StartDateTime >= :t_startdatetime  AND eve.StartDateTime <= :t_enddatetime) OR
                                  (eve.EndDateTime >= :t_startdatetime  AND eve.EndDateTime <= :t_enddatetime) OR
                                  (eve.StartDateTime <= :t_startdatetime   AND eve.EndDateTime >= :t_enddatetime)
                               )];
        
        
        /*Start_Date__c=: Appointment.Start_Date__c order by Start_Date__c asc ] ;*/
        System.debug(eve);
        
        string tshour;
        string tmin;
        string strLs_startdatetime;
        Integer noofslots=0;
        time overLapSlotsTime;
        Integer noofEslots=0;
        time overLapESlotsTime;
        string timeAMPM;
        integer timeHour;
        string timeMin;
        Decimal datediff=0;
        
 /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */       
 /*=========================ERRORS OUT IN THIS BLOCK==============================*/ 
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ if (eve.size()>0) { for(integer z=0;z<eve.size();z++) { if(mapETimeToSlot.get(string.valueof(eve[z].StartDateTime.time())) != null) { // system.debug('+++++++++++++++++++++++++++++++++++++duration'+a[z].Duration__c); overLapESlotsTime=eve[z].StartDateTime.time(); datediff=((Decimal.valueOf(eve[z].EndDateTime.getTime()) - Decimal.valueOf(eve[z].StartDateTime.getTime()))/(1000*60*60))*60; system.debug('datediff '+datediff); if(datediff>30) { noofEslots=integer.valueOf((datediff/30)); system.debug('+++++++++++++++++++++++++++++++++++++noofslots'+noofEslots); for(Integer nctr=0;nctr<noofEslots;nctr++) { if(mapETimeToSlot.get(string.valueof(overLapESlotsTime)).sEvent!=null)
//-------------------------------------------------------------------------------------------
//////////////////////////////////////ERRORS ON ABOVE LINE//////////////////////////////////
//-------------------------------------------------------------------------------------------
 { mapETimeToSlot.get(string.valueof(overLapESlotsTime)).sEventOverlap = eve[z]; mapETimeToSlot.get(string.valueof(overLapESlotsTime)).status='Y'; system.debug('++++++++++++++++++++++++++++++++++++inside overlap'); } else { mapETimeToSlot.get(string.valueof(overLapESlotsTime)).sEvent = eve[z]; system.debug('+++++++++++++++++++++++++++++++++outside overlap'); } overLapESlotsTime=overLapESlotsTime.addMinutes(30); } //mapTimeToSlot.get(string.valueof(a[z].StartDateTime__c.time())).sAppointment = a[z]; }else { if(mapETimeToSlot.get(string.valueof(overLapESlotsTime)).sEvent!=null) { mapETimeToSlot.get(string.valueof(eve[z].StartDateTime.time())).sEventOverlap = eve[z]; } else { mapETimeToSlot.get(string.valueof(eve[z].StartDateTime.time())).sEvent = eve[z]; } } } } } /*=========================================================================================*/
/********************************************THIS BLOCK BELOW WORKS********************************/
/*===========================================================================================*/


if (a.size()>0) { for(integer z=0;z<a.size();z++) { if(mapTimeToSlot.get(string.valueof(a[z].StartDateTime__c.time())) != null) { system.debug('+++++++++++++++++++++++++++++++++++++duration'+a[z].Duration__c); overLapSlotsTime=a[z].StartDateTime__c.time(); datediff=((Decimal.valueOf(a[z].EndDateTime__c.getTime()) - Decimal.valueOf(a[z].StartDateTime__c.getTime()))/(1000*60*60))*60; system.debug('datediff '+datediff); if(datediff>30) { noofslots=integer.valueOf((datediff/30)); system.debug('+++++++++++++++++++++++++++++++++++++noofslots'+noofslots); for(Integer nctr=0;nctr<noofslots;nctr++) { system.debug('+++++++++++++++++++++++++++++++++++++overLapSlotsTime'+overLapSlotsTime); if(mapTimeToSlot.get(string.valueof(overLapSlotsTime)).sAppointment!=null) { mapTimeToSlot.get(string.valueof(overLapSlotsTime)).sAppointmentOverlap = a[z]; mapTimeToSlot.get(string.valueof(overLapSlotsTime)).status='Y'; system.debug('++++++++++++++++++++++++++++++++++++inside overlap'); } else { mapTimeToSlot.get(string.valueof(overLapSlotsTime)).sAppointment = a[z]; system.debug('+++++++++++++++++++++++++++++++++outside overlap'); } overLapSlotsTime=overLapSlotsTime.addMinutes(30); } //mapTimeToSlot.get(string.valueof(a[z].StartDateTime__c.time())).sAppointment = a[z]; }else { if(mapTimeToSlot.get(string.valueof(overLapSlotsTime)).sAppointment!=null) { mapTimeToSlot.get(string.valueof(a[z].StartDateTime__c.time())).sAppointmentOverlap = a[z]; } else { mapTimeToSlot.get(string.valueof(a[z].StartDateTime__c.time())).sAppointment = a[z]; } } } } } /*============================================================================================== for(integer lictr=0;lictr<liETimeSlots.size();lictr++) { system.debug('inside transfer of liETimeSlots to Formated List'); timeAMPM=liETimeSlots[lictr].tstart1.substring(0,5); timeHour=integer.valueof(timeAMPM.substring(0,2)); timeMin=timeAMPM.substring(2,5); system.debug('time hour value'+timeHour); system.debug('time hour value'+timeMin); if (timeHour>12) { timeHour=timehour-12; system.debug('timeHour++++++++++++++++++++++++++'+timeHour) ; timeAMPM=string.valueof(timeHour); if (timeAMPM.length()==1) { timeAMPM='0'+timeAMPM+timeMin+' PM'; } else { timeAMPM=timeAMPM+timeMin+' PM'; } } else { timeAMPM=string.valueof(timeHour); if (timeAMPM.length()==1) { timeAMPM='0'+timeAMPM+timeMin+' AM'; } else { timeAMPM=timeAMPM+timeMin+' AM'; } } liETimeSlots[lictr].tstart1=timeAMPM; //liTimeSlots_form[lictr].sAppointment=liTimeSlots[lictr].sAppointment; } system.debug('liETimeSlots++++++++++++++++++++++++'+liETimeSlots); /*============================================================================================*/ for(integer lictr=0;lictr<liTimeSlots.size();lictr++) { system.debug('inside transfer of liTimeSlots to Formated List'); timeAMPM=liTimeSlots[lictr].tstart1.substring(0,5); timeHour=integer.valueof(timeAMPM.substring(0,2)); timeMin=timeAMPM.substring(2,5); system.debug('time hour value'+timeHour); system.debug('time hour value'+timeMin); if (timeHour>12) { timeHour=timehour-12; system.debug('timeHour++++++++++++++++++++++++++'+timeHour) ; timeAMPM=string.valueof(timeHour); if (timeAMPM.length()==1) { timeAMPM='0'+timeAMPM+timeMin+' PM'; } else { timeAMPM=timeAMPM+timeMin+' PM'; } } else { timeAMPM=string.valueof(timeHour); if (timeAMPM.length()==1) { timeAMPM='0'+timeAMPM+timeMin+' AM'; } else { timeAMPM=timeAMPM+timeMin+' AM'; } } liTimeSlots[lictr].tstart1=timeAMPM; //liTimeSlots_form[lictr].sAppointment=liTimeSlots[lictr].sAppointment; } } } }

 

public with sharing class CEventTimeSlot {
	

	
	// public Time           tStart         {get; set;}
	public string status {get;set;}
	 public String tStart1 {get; set;}
    public Event sEvent {get; set;}
    public Event sEventOverlap {get; set;}

    public CEventTimeSlot(String startTime)
    {
        tStart1 = startTime;
        status='';
        sEvent = null;
        sEventOverlap=null;
    }



}

 

public with sharing class CTimeSlot {
	
	// public Time           tStart         {get; set;}
	public string status {get;set;}
	 public String tStart1 {get; set;}
    public Appointment__c sAppointment {get; set;}
    public Appointment__c sAppointmentOverlap {get; set;}

    public CTimeSlot(String startTime)
    {
        tStart1 = startTime;
        status='';
        sAppointment = null;
        sAppointmentOverlap=null;
    }

}

 

  • November 22, 2011
  • Like
  • 0

I am creating a before insert trigger which pulls some parent fields into a new child record (Opportunity Fields into Quote).  I am pulling two custom fields custom1__c and custom2__c.  When creating the quote, the user can specify values that they would like for custom1__c and custom2__c.  However if the trigger is automatically pulling data from the opportunity for these fields, any input that the user inputs for either of these fields will be overwritten by the trigger.

 

So, I need to add some sort of conditional statement which checks for user input before overwriting.

 

In PHP there is a function named isset() which checks to see if a variable is set.  I'm wondering if there is something similar for APEX.  I think I've seen something about it before, but I can't seem to get the syntax correct.

 

Here's what I would like to do:

 

trigger trgOppQuote on Quote (before insert) {	
   ID ParentOppRecordId = Trigger.new[0].OpptyID__c;
   list<Opportunity> ParentRecord = 
     [SELECT Field1__c, Field2__c FROM Opportunity WHERE id = :ParentOppRecordId ];
	
    String Field1 =  ParentRecord[0].Field1__c;
    String Field2 = ParentRecord[0].Field2__c;
	
	
    for (Quote q : Trigger.new) {
        if(!isset(Trigger.new[0].custom1__c)) q.custom1__c = Field1;
        if(!isset(Trigger.new[0].custom2__c)) q.custom2__c = Field2;
    } 
}

 Thanks in advance for any help!

  • November 03, 2011
  • Like
  • 0

 

 

Hi all, development in the sandbox doesn't need the testing so been busy developing. The assessment controller is stand alone with no object just a page with direction and display controls. I know I am a pain but could someone help please? with comments please as I am very new. ?

Here's my code so far giving me 63% cover:

@isTest
private class AssessmentcontrollerTest
{
        public static testmethod void AssessmentcontrollerTest()
        {
            Boolean isittrue = true;
            final Boolean istrue = True;
           
            PageReference pageRef =Page.AX; // used to set a page           
            test.setCurrentPage(pageRef);  // set starting page
            ApexPages.CurrentPage().getParameters().put('cid', '003R000000Y7Gw4');
            ApexPages.CurrentPage().getParameters().put('cc', 'True');
           
           
            // instanciate and construct the controller class
            Assessmentcontroller AC = new Assessmentcontroller();
                
                // Instantiate a new controller with all parameters in the page
   
        System.debug('Inserting contact detail(single record validation)');
       
        Contact testrec = new Contact(Is_Client__c = True, LastName = 'notlob', Client_Address_1__c = '1 The Rd',
        Client_County__c = 'somecounty', ContactType__c = 'Client', Client_Town__c = 'Bolton', Client_Postcode__c = 'postcode1',
        Client_DOB__c = System.today());
        insert testrec;
       
        //Validate single insert
   
        for(Contact c:[SELECT Is_Client__c,LastName, Client_Address_1__c,Client_County__c, ContactType__c, Client_Town__c, Client_Postcode__c,
        Client_DOB__c  FROM Contact
            WHERE CreatedDate = TODAY
            and Is_Client__c != null]) {
                isittrue = c.Is_Client__c;
            }
       
        System.assertEquals(isittrue, True);

           }    
         
}

****** Controller *******

public class Assessmentcontroller {

    public String conid { get; private set; }   
    public String notclient { get; private set; }   
    public boolean Notcid { get; private set; }   
    public boolean Nocid { get; private set; }   
    public boolean Gotcid { get; private set; }
     
    public Assessmentcontroller(){
    if(ApexPages.currentPage().getParameters().get('cid')!= null){     
        conid = '?cid='+ApexPages.currentPage().getParameters().get('cid'); //assign client record number to conid
        notclient = ApexPages.currentPage().getParameters().get('cc');
            if (notclient == 'false'){
                Notcid = True;
            }
        Nocid = False;
        Gotcid = True;
        }else{
        Nocid = True;
        Gotcid = False;
        }
    }

    public String Id  { get; private set; }
   
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                Id id = ApexPages.currentPage().getParameters().get('cid');
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(               
                      [select name, Is_Client__c,Client_DOB__c, Contact_Ref__c, DNR_Authorisation_Uploaded__c from Contact where Id = :id]));
            }
            return setCon;
        }
        set;
    }
    // Initialize setCon and return a list of records     
    public List<Contact> getContacts() {
         return (List<Contact>) setCon.getRecords();
    }
}

Thanks Steve

Hi,

 

I am having trouble understanding salesforce's bounce management.

 

I've ticked "Activate bounce management" and "Show bounce alert next to all instances of the email address".

 

To test, I gave a Contact an invalid email. Then I clicked the "Send Email" button on that contact's detail page, filled it in and clicked "Send". I did this three or four times. The emails all appear as activities against the contact, and there is no indication that they have bounced. The emailbounceddate is still null for that contact.

 

Should I file a bug, or am I doing something wrong?

 

Thanks in advance

 

s

  • January 09, 2012
  • Like
  • 0

Hi,

 

I am trying to deploy from sandbox to production and it is complaining about not being able to rename standard profiles.

 

The only way I can deploy it is to untick these profiles:

 

Guest License

Chatter Free

Chatter Moderator

Chatter External

 

Surely these profiles should be exactly the same on both systems?

 

I thought at first it must be a version clash, but no, both systems have the winter 12 penguin logo.

 

Any ideas?

 

Thanks

  • January 06, 2012
  • Like
  • 0

Hi,

 

I want to remove some components from my Eclipse project - for example, some profiles. So I pull up "Add or remove Metadata components", untick the components I want to remove, and refresh the project from server. 

 

But the components remain there! The only way I can make them go away is by deleting and re-loading the whole project.

 

Is this a bug, or what am I doing wrong?

 

Thanks

  • January 06, 2012
  • Like
  • 0

When I create a Task using the button in the related list on the Contact object, the task does not appear in the list.

 

I can't use "Relate To" to relate the task to the contact because Contact does not appear in the drop-down.

 

Any ideas? 

 

Thanks

  • January 06, 2012
  • Like
  • 0

If I go to the "Activity History" related list on a Contact record and click "Log a Call" to create a call activity, the call does not appear in the related list. I can use the "Related To" lookup to relate the call to another object, but I cannot seem to get it to show up against the Contact.

 

It would seem to me that a contact is exactly where you want to put a call  - am I missing something?

 

Thanks

  • January 03, 2012
  • Like
  • 0

Hi,

 

I have a visualforce page with one of those salesforce multiselect controls on it where you pick from the left hand box and place the desired options into the right hand box.

 

There is an html label on the control and I need to know what to specify in the "for" attribute for the label. Since the control consists of four different html elements (x_unselected, x_right_arrow, x_left_arrow and x_selected), which one should I associate with the label? Or is it impossible to associate a label with this kind of control?

 

Thanks

 

  • December 15, 2011
  • Like
  • 0

1. The eclipse Git plugin seems to have no way of removing files from source control except by command line.

 

2. I don't want to keep managed packages in source control, but I am unable to remove them even if I DO use the command line! They just keep coming back.

 

I want to roll out Git to the company I work with, and these are looking like show-stoppers, I've spent days ... maybe just missing something obvious? Any help much appreciated!

 

 

 

 

  • November 24, 2011
  • Like
  • 0

I've installed the apex-lang managed package. In eclipse it appears in the managed packages section of the project but if I try to run any methods or instantiate anything it says that the type or method does not exist. If I open any classes it just says "(hidden)".

 

What am I doing wrong?

  • November 22, 2011
  • Like
  • 0

Hi,

 

We're trying to stop DMLExceptions from reaching the user in Visualforce pages which come from a controller. try{} catch{} blocks aren't stopping the message being shown. 

 

Example:

Account a = [select id from Account limit 1];
			try{
				insert a; //fails due to supplied id
			}catch(DMLException ex){}

 From this we get the message:

 

Account ID: cannot specify Id in an insert call - Standard SFDC Exception Message

 

Is there anyway to stop the message being shown? The idea is to build our own message which is more friendly to the user.

 

Looking at the docs shows examples where a custom message is being shown to the user within a try/catch block with no mention of duplicate messages.

 

Any ideas?

 

Thanks for any help.
Rich. 

 

So I have this trigger, which makes a call to a Apex class, which makes a SOQL whenver the function/method is called

 

Apex:

		for(Integer x = 0; x < Trigger.new.size(); x++){
....
			if (ZipCode != NULL && PriBoro == NULL){
				ZipCodeList fillPriBoro = new ZipCodeList();
				fillPriBoro.ZipCode = ZipCode;
				trigger.new[x].Primary_Borough__c = fillPriBoro.getBorough();
			}	
....

 In the ZipCodeList:

public with sharing class ZipCodeList {
...
public ZipCodeList(){}

	public string getBorough (){
		if (ZipCode.length()>=5)
			ZipCode = ZipCode.substring(0, 5);
		
		Borough = [SELECT Borough__c FROM Address__c WHERE Zip_Code__c = :ZipCode];
		
		if (Borough.size()>=1){
			return Borough[0].Borough__c;
		}else {
			return NULL;
		}
	}
	
...
}

 So i read somewhere that in my case everytime that for loop is called from the trigger, it makes soql query call.

 

How would i approach this when each time i call this apex class, I alway need it to return that one Borough data.

 

Hi ,

 i m displaying Products in my viusal force page . I have 3000 products it is giving me following error -:

System.LimitException: Too many script statements: 200001

 

code -

soql ='Select p.Suggested_Price__c, p.Style__c, p.Spec_Sheet__c, p.Size__c ,p. name from Product2 ';

Map<id,Product2> mapAcc = new Map<id,Product2>((List<Product2>)Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 50000'));
            productList=mapAcc.values();
            system.debug('--------productList----------'+productList);
            total_no_of_Records=productList.size();
            if(productList.size()>0){
                total_no_of_pages = productList.size()/noOfRecordPerPage;                 
                if(math.mod(productList.size(),noOfRecordPerPage) > 0){
                   total_no_of_pages = total_no_of_pages +1;
                }
                  for(integer i = 0; i<total_no_of_pages ; i++){
                    integer counter = i+1;
                     for(integer j = pageStartValue ; j< pageEndValue; j++){
                        try{
                            if(productList.size()>j)
                            prolist2.add(productList[j]);
                            
                            for(Product2 p :prolist2){
                                OppProducts pr = new OppProducts(p);                
                                pr.IsSelected = false;
                                listProducts.put(p.id,pr);
                            }
                            mapProducts.put(counter,listProducts.values());
                           
                        }
                        catch(Exception e) {
                        }
                }
                pageStartValue = pageEndValue;
                pageEndValue = noOfRecordPerPage*(i+2);            
                }
                lstProducts=mapProducts.get(selectedPage);
            }

 

I trying to get all products and putting them in a map with size of 25 .So  how can i refine my code so i dont get above error .

 

Thanks

Shailu

  • March 21, 2012
  • Like
  • 0

Hey all,

 

So I have come to a bit of an impass in a trigger I am writting. It may be because it's early and I can't think yet, but I am just not quite sure how to logically solve this problem.

 

Here is the deal, this trigger is responsible for updating a contact associated with a task. When the task is saved, the status field is checked. If the task is completed, an associated date field on the related contact is set to the completion date on the task (if the date to be used for the update is later than the one currently existing). This is to keep track of things such as 'Last stay in touch call', 'Last meeting', etc. The tasks represent interactions with a contact, and when the task is completed they want to mark the contact so they know the last time that kind of action was performed. I have this working perfectly currently.

 

Where it gets complicated is if a task is deleted. They have decided that they want the information to 'roll back' if a task is deleted. They want the field on the contact to be 'recalculated' to find the task that is now the newest that applies to the field that just got deleted. So if the most recent task that set the 'last stay in touch call' gets deleted, they want the system to find the next most recent and use that. This is where I am a bit stuck. The only approach I can think of (while keeping it bulk friendly) is something like:

 

1) Query for all tasks associated with any contact that appeared in this list of newly deleted tasks.
 

2) Iterate over every task. Look to see if the 'Activity_Type__c' matches that of the task that just got deleted for this contact.
 

3) If it is a match on the field, check to see if it most recent than any other entry (could probably eliminate this by sorting the query by the date, and skipping duplicates in my loop). 

 

4) Using the list of tasks, continue with the trigger logic as normal.

 

The issue I have here is, what if one contact is getting multiple tasks deleted at one time? Because when I am iterating through the list of tasks for every contact, I'd have to iterate over every task for them in the trigger context, then find a matching task in the query I just ran, and... argh it gets so complicated and cumbersom. Also, this approach seems excruciatingly inefficient. Does anyone have any better ideas? Below is my code thus far so you can see where I am at. Thanks so much!

 

/**********************************************
Name: ContactActivityRecordTrigger
Author: Daniel Llewellyn
Date 3/14/2012
Description: Will update a contact related to a task when a task is completed. The contact has various date fields that may
                          be populated based on the type of task. Updates performed by the elquoa marketing tool or anyone from 
                          marketing do not fire these updates
***********************************************/                          

trigger ContactActivityRecordTrigger on Task(after insert, after undelete, after update) 
{
    
    try
    {    
        list<Task> tasks;
        if(Trigger.Isundelete)
        {
            tasks = trigger.old;
        }
        else
        {
            tasks = trigger.new;
        }
        //create map of contacts that will contain contacts to update
        map<Id,Contact> contactMap = new map<id,Contact>();
        
        //create a map of users that contain the names of the users related to the tasks.
        map<Id,User> userMap = new map<id,User>();
        
        //we will need to find the DS_Role__c field for all the contacts. So create a map of the contact id, to the contact record
        //so we can run one query, and populate them map, then get the contact details when we need them later without needing
        //to have a query in our loop.
        for (Task thisTask: tasks) 
        {
            //we are only interested in this task if it has a contact, so no contact, just skip adding an entry for this task.
            if(thisTask.WhoId != null)
            {
                contactMap.put(thisTask.WhoId,null);
            }
            if(thisTask.OwnerId != null)
            {
                 userMap.put(thisTask.OwnerId,null);
            }
        }
        
        //populate the map with the id of the contact, then the details about that contact.
        for(Contact con : [select id, DS_Role__c,Last_Meeting_Sales_Call__c,Last_Call__c,Last_Email__c,Last_Demo__c,Last_Mass_Email__c,Last_Sent_Info__c,Last_Marketing_Activity__c from contact where id in :contactMap.keySet()])
        {
            contactMap.put(con.id,con);
        }
    
        //populate the map with the id of the contact, then the details about that contact.
        for(User usr : [select id, Name from User where id in :userMap.keySet()])
        {
            userMap.put(usr.id,usr);
        }
       
       //if this is a delete trigger, the current list of tasks has actually been deleted, so we need to find
       //the task that is now the most recent for each user of the same type that just got deleted
       if(trigger.isDelete)
       {
           //find all the tasks for all the users
           list<task> allTasks = [select id, WhoId, OwnerId,Status,Activity_Type__c, ActivityDate from task where whoId in :contactMap.keySet() order by ActivityDate desc ];
           
           //so now I have to loop over all the tasks I just fetched, and then find all the tasks for the associated contact and see if there is a match and.... arg I have no idea.
           for(Task task : allTasks)
           {
           
           }
       }
       
        //iterate over every task passed in
        for (Task thisTask: tasks)     
        {
            //if this task does not have a contact related to it, then just skip this task and continue.
            if(thisTask.WhoId == null)
            {
                continue;
            }    
            
             //create a reference to the contact associated with this task that we will update
            Contact thisContact =contactMap.get(thisTask.WhoId);
    
            //create a reference to the owner associate with this task
            User thisUser = userMap.get(thisTask.OwnerId);
           
            date activityDate;
            if( thisTask.ActivityDate != null)
            {            
                activityDate = thisTask.ActivityDate;
            }
            else
            {
                activityDate = Date.newInstance(thisTask.LastModifiedDate.year(),thisTask.LastModifiedDate.month(),thisTask.LastModifiedDate.day()); 
            }
            //check if the task status is completed
            if (thisTask.Status.toLowerCase() == 'completed') 
            {                
                //make sure the owner of the task is not eloqua marketing, and make sure the contact's role is not marketing/communications
                if (thisUser.Name.toLowerCase() != 'eloqua marketing' && thisContact.DS_Role__c != 'marketing/communications') 
                {
                    if (thisTask.Activity_Type__c == 'Meeting/Sales Call' && (activityDate > thisContact.Last_Meeting_Sales_Call__c || thisContact.Last_Meeting_Sales_Call__c == null) ) 
                    {
                        thisContact.Last_Meeting_Sales_Call__c = activityDate;
                    }
                    else if (thisTask.Activity_Type__c == 'Call' && (activityDate > thisContact.Last_Call__c ||  thisContact.Last_Call__c == null))
                    {
                        thisContact.Last_Call__c = activityDate;
                    }
                    else if (thisTask.Activity_Type__c == 'Email' && (activityDate > thisContact.Last_Email__c || thisContact.Last_Email__c == null))
                    {
                        thisContact.Last_Email__c = activityDate;
                    }
                    else if (thisTask.Activity_Type__c == 'Demo' && (activityDate > thisContact.Last_Demo__c || thisContact.Last_Demo__c == null)) 
                    {
                        thisContact.Last_Demo__c = activityDate;
                    }
                    else if (thisTask.Activity_Type__c == 'Mass Email' && ( activityDate > thisContact.Last_Mass_Email__c || thisContact.Last_Mass_Email__c == null)) 
                    {
                        thisContact.Last_Mass_Email__c = activityDate;
                    }
                    else if (thisTask.Activity_Type__c == 'Sent Info' && ( activityDate > thisContact.Last_Sent_Info__c || thisContact.Last_Sent_Info__c == null ))
                    {
                        thisContact.Last_Sent_Info__c = activityDate;
                    }
                    else 
                    {
                        if (thisTask.ActivityDate > thisContact.Last_Marketing_Activity__c || thisContact.Last_Marketing_Activity__c == null) 
                        {
                            thisContact.Last_Marketing_Activity__c = activityDate;
                        }          
                    }
                }
            }
            contactMap.put(thisContact.id,thisContact);
        }
   
        //we don't need an all or nothing update, so use database.update with the all or nothing flag set to false
        if(!contactMap.values().isEmpty())
        {
            database.update(contactMap.values(),false);
        }
    }    
    catch(exception e)
    {
        system.debug('Error occured updating related contact' + e);
        
        //Send an email to the admin after an error occures
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'Kenji776@gmail.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Error in ContactActivityRecordTrigger');
        mail.setPlainTextBody('An error occured while running the trigger.' + e.getMessage() + ' On Line Number ' + e.getLineNumber());
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });        
    }    
    
}

 

I have the following trigger that needs to have a test method before I can deploy it and would like any advice on how to do this.

 

 

trigger createworkorder on Opportunity (after update)
{
if(trigger.new[0].StageName=='closed won'&&(trigger.old[0].StageName<>'closed won'))
{
Work_Order__c obj=new Work_Order__c(Opportunity__c=trigger.new[0].id);
insert obj;
case c1=new case(Status='new',Subject='Create Product Cases for Work Order',Work_Order__c=obj.id);
insert c1;
}
}

Hello,

 

I have a trigger in which I need to lookup fields using a lookup field.

If I debug/print out value of "Primary_Partner__c" in my trigger this works correctly.  However when I try to lookup fields using "Primary_Partner__r.Name" or similar for other fields I cannot find or obtain the values.  Is there a restriction in triggers from looking up a parent object or could this be related to some settings on the field?

 

Thanks

Hey all,

 

Sometimes I need to wipe off data from certain tables to simulate a more accurate use case for my test methods. But I'm wondering if it's entirely safe to call delete on a table? I know that the data is only deleted for that particular test case, but does anybody know how exactly this happens? Is it just a "pretend delete?"

 

I'm having some "what-if" concerns, like, what if all of a sudden SF crashes? Will I have to resort to voodoo in order to get my data back? Basically, how safe is it to call delete on a table in a test case?

 

Thanks much!

 

P.S> I know that API v24.0 runs test cases without looking at the existing org data, but there's some dependency between my tests and the org data. So, that's not really what I'm looking for here.

Hi

I have created a

Map<id, id> MapEvApp = new Map<id, id>();

i added event id and event.appointment id into map

 

Now i am using the Map as 

MapEvAppId.get(appointup_eventid[i].id).id) ;

Where appointid_event is alist of oppintment which contains field when app id = id in set;

 

But when i use the map to get  event id before saving i am getting this error

Error: Compile Error: Initial term of field expression must be a concrete SObject: Id at line 127 column 110

 

Thanks

Anuraj

 

I would like to know what is the better design for the database.  The application uses Visual Force pages to perform CRUD methods on a custom object and at least 8 related list objects.  Each record of the custom object has about 5-50 records in each of the related lists.  A majority of the time only a single custom object record and its related lists is queried.

 

1. Is it be better to create a single related list object with a field that specifies the related list type in lieu of the 8 related list objects?  In this case all the fields on each of the 8 related lists objects would be put in the single object.  However, many of these fields obviously would be null. 

 

2. Is there a performance difference between doing 8 queries and 1 query where the same number of records are returned in both cases?  In the case of the single query, the records would be filtered thru code to put them into appropriate lists and is the 8 query method more efficient?

 

3. Is there a performance difference when a query when 10 fields are returned in a query versus 100 fields are returned in a query?  The 100 field query would be filtered thru code to put them into appropriate lists.

 

4. Is there a storage taken up by fields that are null in an object?

 

Thanks

 

 

 

  • March 12, 2012
  • Like
  • 0

I'm just starting out on apex coding and I understand that triggers aren't actually executed per record, but in batches. I just wanted to confirm something

 

 for (Task tasksToUpdate: trigger.new)

 

Does the above for statement sufficiently capture all tasks that might execute the trigger at the same time? Or do I have to do something like an array assignment to update this? Can anyone provide a sample?

Very simple scenario: take a string, encode it, then display the encoded characters. And it gives this error:

BLOB is not a valid UTF-8 string

 

Code:

Blob key = Blob.valueOf('asdfghjkzxcvbnml'); // 16 bytes
Blob iv = Blob.valueOf('asdfghjkzxcvbnmn'); // 16 bytes
String u = 'X';
Blob uenc = Crypto.encrypt('AES128', key, iv, Blob.valueOf(u));
system.debug(uenc.tostring()); // BREAKS HERE

 

Any ideas why this is happening?! Thanks.

 

Hi

 

I Am getting this error because of for  loops , but when am trying to customize the for loops, my functionality is changing ,Please let me know there is any alternative solution for it.

 

Thanks in Advance.

HI,

 

I have a object "Key Combination Lookup" to which i have given "Read only" permissions to other users .ie. users cannot create or edit a Key Combination Lookup record.

 

I have a trigger on Account. On insert of account, the trigger creates a Key combination lookup record. The relationship between the Account and Key Combination lookup is a Lookup relationship.

 

Now, when other users create an account, the trigger is creating a key combination lookup record. I dont understand why this is happening, since the users do not have create permissions on key combination lookup object. 

 

Is it that trigger is executing in system mode? 

 

Thanks,

Shailesh.

Hi - I have a client request I'm struggling with, and would value any ideas.

 

I have members (Member__c as parent) that take awards (Award__c as child). Awards expire after time and have to be updated.

 

Certain high level awards require a combination of other awards before the member can qualify for awards. The client has asked to be able to add simple logic that determines which awards are required to gain the higher awards.

 

So I've set-up 5 look-up fields so that the user can select up to 5 awards needed to qualify for the higher level award.

And created a text field to enter a logic expressions - something like (AwardA OR AwardB) AND AwardC - a bit like the 'Add Filter Logic' when setting up a workflow.

 

So what I need to do is to check through all of the valid awards held by the member, and see if they have the awards required with the specified logic.

 

I can use a formula and SUBSTITUTE commands to create a query string using the user enter logic - 

 

Award_Type4__r.Qualifications_Awards__c.Name='SLSGB Assessor Update' OR Award_Type4__r.Qualifications_Awards__c.Name='SLSGB IRB Assessor'

 

and I can build this into a full query string. 

 

I have tried putting this into a query, but as I need to query from the parent, I'm struggling to get it to work..

 

I tried this:

 

Member__c[] members = [Select id, (select id from Awards__r  WHERE ((Award_Type4__r.Qualifications_Awards__r.Name='SLSGB Assessor Update' OR Award_Type4__r.Qualifications_Awards__r.Name='SLSGB IRB Assessor') AND Member__c=:memberid)) from Member__c WHERE id=:memberid];

 

but seem to get 1 result each time regardless of the awards held by the Member.

 

I'm not even sure a SOQL is the correct approach - I did consider putting all of the valid awards held by the member into a set, then uses the set.CONTAINS() to see if the required awards existed, but not sure how to apply the logic requirement with this approach.

 

Any ideas ?

 

Many thanks.