• Chidambar Reddy
  • SMARTIE
  • 939 Points
  • Member since 2013
  • SFDC Developer
  • Dhruvsoft


  • Chatter
    Feed
  • 28
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 170
    Replies
Hi,
I am getting bellow error while adding a record into projects object, what is this exactly mean.

Error: Invalid Data. 
Review all error messages below to correct your data.
You must have a Group Name in order to create Projects. Contact an LM2 Admin in order to correct.
This is my trigger but I am getting an error Trigger has hit a max query size:50001

The following trigger is trying to populate a lookup field APA on child account. This value is based on the value in another field call APA_Name__c which is populated as a text field on child account. I have 3 accounts of APA . . Please can someone help on this.

Trigger PopulateAPA on Account (before insert,before update) {

  // Get a list of all active record types within the system associated to Accounts
        List<Account> APAList = [Select Name, Id From Account];

        // Create a map between the Account record Type Name and Id for for easy retrieval
        Map<String,String> NewAPA = new Map<String,String>{};
                  
            for(Account APAAcc: APAList)
                NewAPA.put(APAAcc.Name,APAAcc.Id); 

  for (Account NewAccount : Trigger.new)
  {
  If(NewAccount.APA_Name__c == 'Global Heat Source')
      {
     
      NewAccount.APA__c = NewAPA.get('Global Heat Source');
       
       } 
  else If(NewAccount.APA_Name__c == 'Forrest')
      {
     
      NewAccount.APA__c = NewAPA.get('Forrest');
      }
  else If(NewAccount.APA_Name__c == 'Keepmoat')
      {
     
      NewAccount.APA__c = NewAPA.get('Keepmoat');
      }
   }
   }
Hello Every one
I am integarting with the other product,The phone number in salesforce.com is using (614)-903-5444
But i need to parse has 614-903-5444

How to remove the values.

Thanks a lot

Regards
Jyo


 
Hi All,

I am trying to render few fields based on the value of a picklist field. When the value of Picklist is changed to Old then only fields A, B, C must be shown. When the Value of Picklist is changed to New then all 5 fields A,B,C,D, E must be shown. Please help me on how to show two different conditions in Visualforce page tag for a Picklist field. 

Following is the code.

 <apex:inputField value="{!A}"  rendered="{!Picklist == 'New'}"/>
  <apex:inputField value="{!B}" rendered="{!Picklist == 'New'}"/>
   <apex:inputField value="{!C}"  rendered="{!Picklist == 'New'}"/>
  <apex:inputField value="{!D}" rendered="{!Picklist == 'New'}"/>
   <apex:inputField value="{!E}"  rendered="{!Picklist == 'New'}"/>
 
I was able to show all 5 fields when Picklist value is New. How can I add anther condition? Any help would be highly appreciated.

Thanks,
Raghu

 
Hi,

How to reset Sandbox account's password in Production account?

Thanks
Hi,

I have added a 4 custom fields to Account object. Then I have edited the current layout and add those 4 custom fields as a new section called "Account Sub Info". Now I want to package my 4 custom fields and the "Account Sub Info" section.

Means when user installs my package I want my custom fields and "Account Sub Info" section added to their Account layout.

How can I do this?

When packaging I tried to package the "Account Layout". When I try to install it it says the follwing.

Duplicate Name         The name "NewOpportunity" is already used on component type: Action. Please rename existing component.
Duplicate Name         The name "NewNote" is already used on component type: Action. Please rename existing component.
Duplicate Name         The name "NewTask" is already used on component type: Action. Please rename existing component.
Duplicate Name         The name "NewContact" is already used on component type: Action. Please rename existing component.
Duplicate Name         The name "NewCase" is already used on component type: Action. Please rename existing component.
Duplicate Name         The name "Account-Account Layout" is already used on component type: Page Layout. Please rename existing component.
Duplicate Name         The name "NewEvent" is already used on component type: Action. Please rename existing component.
Duplicate Name         The name "LogACall" is already used on component type: Action. Please rename existing component.
Duplicate Name         The name "Account.Billing" is already used on component type: Custom Button or Link. Please rename existing component.


Please Help and guide me how can I achive my requirement.

Thanks in advance...
Hi all,
we have reached 64% in Data Storage, Is there any possibilities to Archive records?
There are 2 possibilities to solve this problem.
One way is to puchase additional sapce from salesforce
and anothere one is to backup our records and delete them.
Please tell me is there any other methods avalibale to resolve this issue.
Please send me the link.
Thanks and Regards 
S Mohan
I created a custom Object "Location" , all are 3 picklists and each other dependent picklists hirarchely.  

User-added image

I am getting Duplication entries from these fields.
when i select HeadQuarter there can be multiple Areas should be enter but once i select one Area in one HeadQuarter,
the selected Area should not save again in the record .

To avoid this which criteria should i follow,

Workflow
Validation Rule
Trigger

Which one is suitable and how.

Is there any other Good Apporach .


 
public with sharing class CaseEmailClass
{   Public Contact cc{get;set;} 
    Public list<Contact> cn{get;set;}
    public String Comment { get; set; }
    public String Emailid { get; set; }
    public String ContactNo { get; set; }
    public String Name { get; set; }
    public PageReference submit() 
   {
   cn=[SELECT Id,Email FROM Contact];
   if(cn.Email==EmailId)
   {
    Case c=new Case();
            c.Status='New';
            c.ContactId=cn.id;
            c.Priority='High';
            c.Description=Comment;
            c.Subject='A New Case Has Been Rasied';
           insert c;
           }
  
   List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      mail.setToAddresses(new String[] {'mail2gattam@gmail.com'});
       mail.setSubject('A New Case Has Been Raised');
     String table = '';
      String body='';
        /*     table=table+'Name:'+Name+'<br/>'; 
             table=table+'ContactNo:'+ContactNo+'<br/>';
             table=table+'Email Id:'+Emailid+'<br/>';
             table=table+'Comment:'+Comment+'<br/>'; */
          table = table + '<b><table  align="center" width="50%"  border: 1px solid black;>'; 
                  table = table + '<tr>';
                  table = table + '<td width="25%" align="center"><b>Name:&nbsp;&nbsp;</b>'+Name+'</td>'; 
                  table = table + '</tr>';
                  table = table + '<tr>';
                  table = table + '<td width="25%" align="center"><b>ContactNo:&nbsp;&nbsp;&nbsp;</b>'+ContactNo+'</td>'; 
                  table = table + '</tr>';
                  table = table + '<tr>';
                 table = table + '<td width="25%" align="center"><b>Email Id:&nbsp;&nbsp;&nbsp;</b>'+Emailid+'</td>';
                 table = table + '</tr>';
                 table = table + '<tr>';
                  table = table + '<td width="25%" align="center"><b>Comment:&nbsp;&nbsp;&nbsp;&nbsp;</b>'+Comment+'</td>'; 
                   table = table + '</tr>';
              body=table;
        mail.setHTMLbody(body);      
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });   
       // return null;
          Contact con= New Contact();
          con.LastName=Name;
          con.MobilePhone=ContactNo;
          con.Email=EmailId;
        insert con;
            Case c=new Case();
            c.Status='New';
            c.ContactId=con.id;
            c.Priority='High';
            c.Description=Comment;
            c.Subject='A New Case Has Been Rasied';
           insert c;
         return null;
   }
    }
Hello All,

I am sure you see requests all the time to aid in the creation, modification and testing of new APEX code from greenhorns like myself. The code below is complete and helps with a custom attachment object that replaces the standard Notes & Attachments section on Contracts. The code, object and process works great in the Sandbox environment but I am having difficulties testing the code.

I have browsed through the forums looking and have been researching online for best practices on testing APEX coding in general and have been unable to tackle the project fully. If anyone could assist, I would greatly appreciated it!

User-added image
public class UploadContractAttachmentController {
    
    public String selectedType {get;set;}
    public String description {get;set;}
    private Contract contract {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    public UploadContractAttachmentController(ApexPages.StandardController controller) { 
        this.contract = (Contract)controller.getRecord();
    }   
    
    // creates a new Contract_Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Contract_Attachment__c obj = new Contract_Attachment__c();
        obj.contract__c = contract.Id; 
        obj.description__c = description;
        obj.type__c = selectedType;
        // fill out cust obj fields
        return Database.insert(obj);
    }
    
    // create an actual Attachment record with the Contract_Attachment__c as parent
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // inser the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Contract_Attachment__c record
    *  2. Insert new Attachment with the new Contract_Attachment__c record as parent
    *  3. Update the Contract_Attachment__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
        try {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
        
            if (customAttachmentResult == null || !customAttachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));
                return null;
            }
        
            Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
        
            if (attachmentResult == null || !attachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));            
                return null;
            } else {
                // update the custom attachment record with some attachment info
                Contract_Attachment__c customAttachment = [select id from Contract_Attachment__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+contract.Id);
    }
    
    public PageReference back() {
        return new PageReference('/'+contract.Id);
    }     
 
}

 
So, I've managed to learn a bit of apex. Now I really need a hand with testing the code so that I can move it to production.  Could someone please help me with the following?
public class multiAddCEx {

public Id cID = ApexPages.currentPage().getParameters().get('Id'); //grab the Vendor Bill ID
//Integer count = 0;
string num_name = '';
// Lookup against Available Cost Codes Junction Object
public List<SelectOption> costcodes {get; set;}
    public multiAddCEx ()
    {
        costcodes  = new List<SelectOption>() ;
          for(Cost_Code_Connection__c cc : [select Cost_Code_Junction2__r.Cost_Code_ID__c , Cost_Code_Percentage__c, id,name from Cost_Code_Connection__c where Cost_Code_Connection__c.Bill_Item_Junction__c =: cID order by Cost_Code_Junction2__r.Cost_Code_ID__c, Cost_Code_Percentage__c ])
        {
        costcodes.add(new SelectOption(cc.Cost_Code_Junction2__r.Cost_Code_ID__c +' - '+ cc.Cost_Code_Percentage__c +'%',cc.Cost_Code_Junction2__r.Cost_Code_ID__c +' - '+ cc.Cost_Code_Percentage__c +'%' )) ;
        }
  }
//Lookup to find User Intranet ID in User records
public List<SelectOption> intranetids {get; set;}
    {
        intranetids = new List<SelectOption>() ;
        intranetids.add(new SelectOption('-Select-','-Select-'));
        for(User ui : [select Intranet_ID__c , id, name, IsActive from User where IsActive = True order by Intranet_ID__c])
                {
if (ui.Intranet_ID__c != null){ 
num_name = ui.name;
        intranetids.add(new SelectOption(ui.Intranet_ID__c, ui.Intranet_ID__c +' - '+ num_name  )) ;
}
        }    
    }
List <Bill_Allotment__c> CExList;
public Id getID {get; set;}
public PageReference reset()  { //pull at most 8 expense records to show so we don't clutter up the page
CExList = [select name, Bill_Allotment__c.Phone_Number__c ,  Allotment_Amount__c, Bill_Allotment__c.Allotment_User_Id__c,  Bill_Allotment__c.Bill_Cost_Code__c  from Bill_Allotment__c where Bill_Item__c =: cID order by createddate limit 0 ];
return null; }
public List <Bill_Allotment__c> getCExs() {
 if(CExList == null) reset();
 return CExList;
  }
public void setAccounts(List <Bill_Allotment__c> cexs) {
   CExList = cexs;}
public PageReference save() {//upsert records on save
try{
       upsert CExList;
       ApexPages.Message myMsg = new ApexPages.message(ApexPages.Severity.Info, 'Records Saved Successfully'); //show confirmation message on save
ApexPages.addMessage(myMsg);
return null;   
       }
    catch(DmlException ex){
   
        ApexPages.addMessages(ex);
       }
    return null;       
}
//ApexPages.Message myMsg = new ApexPages.message(ApexPages.Severity.Info, 'Records Saved Successfully'); //show confirmation message on save
//ApexPages.addMessage(myMsg);
//return null;}
public PageReference cancel() {//close window without upsert
return null;
}
public PageReference add() {
//count++;
CExList.add(New Bill_Allotment__c(Bill_Item__c = cID)); //add records to Bill Items and associate with current Bill
return null; }
 //public Integer getCount() {
        //return count;
   // }
}
Hello Everyone,
I  am making a callout to external webservices ,I am not getting any error ,
Here is my problem ,When i update values on contact that wont value are not passing to external webservices.
Its passing the random records.
Below is my trigger code and apex Class

trigger Rephistorytracking on contact (after update,before update) {  
    RepTriggerHandlerclass contactHandler = new RepTriggerHandlerclass ();
    Jcoreutil    JcoreHandler= new Jcoreutil();
    if(Trigger.isAfter && Trigger.isUpdate) {
        contactHandler.onAfterUpdate(Trigger.New, Trigger.oldMap);
    }
    
    if(Trigger.IsAfter && Trigger.isUpdate)
    {
        contactHandler.onAftercontactUpdate(Trigger.New);
    }
     if(Trigger.IsUpdate && Trigger.isBefore)
    {
         Jcoreutil.JcoreAdd();
    }
 
}

###################APEX CLASS####################################


public class Jcoreutil {
     @future(callout=true)
     public static void JcoreAdd()
      {
        Set<Id> TerminateCntId= new Set<Id>();
        Set<Id> RepIdsValue= new Set<Id>();
        List<Id> CntListIds= new List<Id>();
        List<contact> TerminateCntList= new List<contact>();
        String LicenseNumber;
         for( contact TerminateCntQuery :[Select Id,Name,CRD__c,FirstName,LastName,Middle_name__c,Gender__c,Address_Type__c,
                                          MailingStreet,MailingCity,MailingState,MailingPostalCode,Email,MobilePhone,
                                          QAM_DSP__r.Name,QAM_DSP__r.CRD__C,QCC_DSP__r.CRD__C,QAM_DSP__r.FirstName,
                                           QAM_DSP__r.LastName,QCC_DSP__r.FirstName,QCC_DSP__r.LastName,Birthdate,Rep_Status__c,
                                           QCC_DSP__c,Term_Date__c,Start_Date__c,LastModifiedDate,HomePhone,Phone,OtherPhone
                                            from Contact where (Rep_Status__c='Terminated'OR Rep_Status__c='Converted') Limit 1])
         {
              system.debug('TerminateQuery@@@@'+TerminateCntQuery);
               if(TerminateCntQuery.Rep_Status__c=='Converted')
               {         
             TerminateCntList.add(TerminateCntQuery);
             TerminateCntId.add(TerminateCntQuery.id);
             List<License__c> lstLicensesValues=new List<License__c>();
             License__c LicensesValues=[Select Id,License__c from License__c where contact__c  IN:TerminateCntId Limit 1] ;
             lstLicensesValues=[Select Id,License__c from License__c where contact__c  IN:TerminateCntId];
             integer LicensesValue;
             LicensesValue=lstLicensesValues.size();

Please help me

I Tried to pass the list of ids,but its give error while calling method in trigger.

Thanks.

Regards,
Jyo
 
Hi All,
How to use upsert method in apex class.
Hi folks,
    Can anyone tell me what is the purpose of HasOptedOutOFEmail in contact and lead object

Thanks in advance
Karthick
hi i have two fields-
"Days Needed"-- Manual Entry
"Days Remaining"-- Should be a formula field in which when each day passes it subtract 1 from "Days Needed" and populate the value and stop when it is 0.
  let say "Days Needed" field has value-2 and today is 30th . on 31st the value in "Days Remaining" should be-1 and on 1st value on "Days Remaining" should be 0;
I have a Custom Button 'New Vehicle' for a Custom Object which is a related list of Case.
This has a Javascript

window.open("/apex/CaseVehicles2?id="+{!Case.Id}  + ,'_blank','toolbar=no, scrollbars=yes, resizable=yes, top=300, left=300, width=1200, height=600, location=no, titlebar=no, menubar=no');

And for the life of me,  will not work and give me the error "identifier starts immediately after numeric literal".

Strangely enough, when I change merge field to a CaseNumber --  {!Case.CaseNumber}  it works fine.  But Case.id will not work

Am I missing something obvious ? 

Thanks



Hi I have written a trigger on a custom object call Job__c which has a lookup relationship to Account. This trigger is updating a field from Job on the Account record when the Job__c is the first related list. However, I just realized trigger only works for each time a job is either inserted or edited. 

How can I update all the existing Accounts with their jobs all at the same time? The first is a date/time field that is updating from Job to Account. I need to run a report for all the Accounts. Now I need to run a batch apex class. '

But what I don't understand is how the batch apex is run. Does it call it trigger class or trigger calls the batch class? I need the batch to happen only once so that all my existing accounts get updated. Then I can keep my trigger active for all the new job that comes in.

I have read the salesforce doc about batch apex and searched multiple times but I'm still not understanding how it works.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_batch_interface.htm

Here's my working trigger: 
trigger NewJobTimeStampOnAccount on Job__c (after insert, after update) {

  Map<ID, Account> parentAcct = new Map<ID, Account>(); //Making it a map instead of list for easier lookup
  List<Id> listIds = new List<Id>();
 
if(trigger.isInsert || trigger.isUpdate){
  for (Job__c childObj : Trigger.new){
    listIds.add(childObj.Account__c);
   
  }
}
  //Populate the map. Also make sure you select the field you want to update, amount
  //The child relationship is more likely called jobs__r (not job__r) but check
  //You only need to select the child jobs if you are going to do something for example checking whether the job in the trigger is the latest
  parentAcct = new Map<Id, Account>([SELECT id, New_Job_Start_Date__c, (SELECT ID, Date_Time_Taken__c FROM Jobs__r) FROM Account WHERE ID IN :listIds]);
 
  List<Job__c> i = [select id from Job__c where Account__c in :listIds order by Date_Time_Taken__c ASC limit 2];


  for (Job__c job: Trigger.new){
       if(i[0].id == job.id && job.Account__c != null)
     {
        Account myParentAcct = parentAcct.get(job.Account__c);
        if(myParentAcct != null)
        myParentAcct.New_Job_Start_Date__c = job.Date_Time_Taken__c;
       
     }
  }
  update parentAcct.values();
 

}

Please help me understand how should I be writing my batch class? How does batch class updated multiple records at the same time or how does it know to update ALL the accounts in my org at the same time? 

Hi All,

Thanks in advance and I'll try to be brief:
  1. I've created an app called Marketplace Tracker to help manage our vacation rental business.
  2. The main object is Marketplace within which the records detail the the various vacation rental websites (marketplaces) we manage.
  3. I'm currently in the schema builder adding objects / relationships in an effort to map out the app before I get down to the nitty gritty.
  4. I have a master detail relationship from the Marketplace object to another (child) object called Geographic Region.
  5. And I have another master detail relationship from the Geographic Region object to another (child) object called Country.
  6. Then I have another master detail relationship from the Country object to another (child) object called State or Province.
Now is where the (non) fun begins:

For some strange reason I'm unable to repeat the straightforward process above by creating another master detail relationship from the State or Province to another (child) object called City. Specifically, when I drag the master detail relationship on to the child object (City) the related object (State or Province) does not appear in the drop down.

Even stranger is that, as a test, I've deleted the master detail relationship between Country and State or Province only to find that I can then create a master detail relationship between State or Province and City, but then when I go back to re-create the master detail relationship between Country and State or Province (the one I deleted) the related object (Country) does not appear in the related drop down!

Any help is much appreciated. 
I am trying to create a trigger that will count activities (tasks) on leads.
My code is below....

When saving I am getting the following error....

Error: Compile Error: unexpected token: '}' at line 30 column 1

But if I remove the curly bracket I get a different error

Error: Compile Error: unexpected token: '<EOF>' at line 30 column 0


trigger TaskUpdateLead on Task (after delete, after insert, after undelete, after update)
{
Set<ID> LeadIds = new Set<ID>();

//We only care about tasks linked to Leads.

String leadPrefix = Lead.SObjectType.getDescribe().getKeyPrefix();

//Add any Lead ids coming from the new data

if (Trigger.new != null) {
    for (Task t : Trigger.new) {
     if (t.WhatId != null && string.valueOf(t.whatId).startsWith(leadprefix) )
         {LeadIds.add(t.whatId);
      }
   }
}
//Also add any Lead ids coming from the old data (deletes, moving an activity from one Lead to another)

if (Trigger.old != null) {
    for (Task t : Trigger.old) {
     if (t.WhatId != null && String.valueOf(t.whatId).startsWith(leadprefix) )
         { LeadIds.add(t.whatId);
      }
   }
}
if (LeadIds.size() > 0)

Lead.Activity_Count__c.updateLeadCount<LeadIds>
}


Any guidance is very much appreciated.
Hello Everyone,

I have accidentally updated a field value to blank in the trigger, How can I revert it back?
Hi,
I am getting bellow error while adding a record into projects object, what is this exactly mean.

Error: Invalid Data. 
Review all error messages below to correct your data.
You must have a Group Name in order to create Projects. Contact an LM2 Admin in order to correct.
hi friends....can any one send me examples of visuval force examples.............kakarlarams@gmail.com
I am new at force.com dev and I am working in a project that need to do one trigger after insert that works like this:

I will add an Opportunity, that have a field called "Contact by" (Multi-select picklist, values: email, phone), when value is email, The trigger will create a TASK and the field Subject of task get value of "Contact by" and ActivityDate get today + 5 days.

I know that work with workflows and its the best pratices, but I want to make this on a trigger, could you help me ?
Hi All,

i am getting too many soql limt exceed error when my below class executed. Please help me on this. This is very urgent.

public class ProjectUtil{  
   
    public static void beUpdate(List<OpportunityLineItem > listOLIList){
        Project_Assay__c PrjAssay;
for (OpportunityLineItem OppLI: listOLIList) {
            
  PrjAssay=[select id,name,Assay_Number__c,Sales_Price__c, Study_Number__c,OppAssay__c,
                                    from Project_Assay__c where OppAssay__c=:OppLI.OppAssay__c];                   
                           
                            PrjAssay.Assay_Number__c=OppLI.ProductCode;
                            PrjAssay.Quantity__c=OppLI.Quantity;
                            PrjAssay.Study_Number__c=OppLI.Study_Number__c;
                            PrjAssay.OppAssay__c=OppLI.OppAssay__c;
                            PrjAssay.Sales_Price__c=OppLI.UnitPrice;
                            
        }
         update PrjAssay;
    
    }
    
}

Thanks,
Yarram
  • February 02, 2015
  • Like
  • 0
This is my trigger but I am getting an error Trigger has hit a max query size:50001

The following trigger is trying to populate a lookup field APA on child account. This value is based on the value in another field call APA_Name__c which is populated as a text field on child account. I have 3 accounts of APA . . Please can someone help on this.

Trigger PopulateAPA on Account (before insert,before update) {

  // Get a list of all active record types within the system associated to Accounts
        List<Account> APAList = [Select Name, Id From Account];

        // Create a map between the Account record Type Name and Id for for easy retrieval
        Map<String,String> NewAPA = new Map<String,String>{};
                  
            for(Account APAAcc: APAList)
                NewAPA.put(APAAcc.Name,APAAcc.Id); 

  for (Account NewAccount : Trigger.new)
  {
  If(NewAccount.APA_Name__c == 'Global Heat Source')
      {
     
      NewAccount.APA__c = NewAPA.get('Global Heat Source');
       
       } 
  else If(NewAccount.APA_Name__c == 'Forrest')
      {
     
      NewAccount.APA__c = NewAPA.get('Forrest');
      }
  else If(NewAccount.APA_Name__c == 'Keepmoat')
      {
     
      NewAccount.APA__c = NewAPA.get('Keepmoat');
      }
   }
   }
Hello All,

I am sure you see requests all the time to aid in the creation, modification and testing of new APEX code from greenhorns like myself. The code below is complete and helps with a custom attachment object that replaces the standard Notes & Attachments section on Contracts. The code, object and process works great in the Sandbox environment but I am having difficulties testing the code.

I have browsed through the forums looking and have been researching online for best practices on testing APEX coding in general and have been unable to tackle the project fully. If anyone could assist, I would greatly appreciated it!

User-added image
public class UploadContractAttachmentController {
    
    public String selectedType {get;set;}
    public String description {get;set;}
    private Contract contract {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    public UploadContractAttachmentController(ApexPages.StandardController controller) { 
        this.contract = (Contract)controller.getRecord();
    }   
    
    // creates a new Contract_Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Contract_Attachment__c obj = new Contract_Attachment__c();
        obj.contract__c = contract.Id; 
        obj.description__c = description;
        obj.type__c = selectedType;
        // fill out cust obj fields
        return Database.insert(obj);
    }
    
    // create an actual Attachment record with the Contract_Attachment__c as parent
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // inser the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Contract_Attachment__c record
    *  2. Insert new Attachment with the new Contract_Attachment__c record as parent
    *  3. Update the Contract_Attachment__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
        try {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
        
            if (customAttachmentResult == null || !customAttachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));
                return null;
            }
        
            Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
        
            if (attachmentResult == null || !attachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));            
                return null;
            } else {
                // update the custom attachment record with some attachment info
                Contract_Attachment__c customAttachment = [select id from Contract_Attachment__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+contract.Id);
    }
    
    public PageReference back() {
        return new PageReference('/'+contract.Id);
    }     
 
}

 
Hi All,
How to use upsert method in apex class.
I am trying to create a trigger that will count activities (tasks) on leads.
My code is below....

When saving I am getting the following error....

Error: Compile Error: unexpected token: '}' at line 30 column 1

But if I remove the curly bracket I get a different error

Error: Compile Error: unexpected token: '<EOF>' at line 30 column 0


trigger TaskUpdateLead on Task (after delete, after insert, after undelete, after update)
{
Set<ID> LeadIds = new Set<ID>();

//We only care about tasks linked to Leads.

String leadPrefix = Lead.SObjectType.getDescribe().getKeyPrefix();

//Add any Lead ids coming from the new data

if (Trigger.new != null) {
    for (Task t : Trigger.new) {
     if (t.WhatId != null && string.valueOf(t.whatId).startsWith(leadprefix) )
         {LeadIds.add(t.whatId);
      }
   }
}
//Also add any Lead ids coming from the old data (deletes, moving an activity from one Lead to another)

if (Trigger.old != null) {
    for (Task t : Trigger.old) {
     if (t.WhatId != null && String.valueOf(t.whatId).startsWith(leadprefix) )
         { LeadIds.add(t.whatId);
      }
   }
}
if (LeadIds.size() > 0)

Lead.Activity_Count__c.updateLeadCount<LeadIds>
}


Any guidance is very much appreciated.