• sfck
  • NEWBIE
  • 375 Points
  • Member since 2011

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

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

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

 

 

 

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.