1

I have a class that allows users via VF to select custom contact roles for their opportunity. I need them to select at least one (or only one) of the contacts as primary. I know this should be fairly simple to do in the class but so far the best I can do is make it validate no matter what you do or not at all. I also tried an after the fact trigger but that isn't working for my need either because it doesn't wait until all the custom contacts are added, it just triggers after the first one and the first one might not be checked as primary. I should just be able to tell it to do a quick list or something just before the class saves to verify that yes one of the contacts selected is marked as primary.

Here is my class without my sad attempts at validating.

public with sharing class opportunityContactEntryExtension {

   public Opportunity theOpp {get;set;}
   public String searchString {get;set;}
   public Opportunity_Contact_Role__c[] chosencontacts {get;set;}
   public contact[] availablecontacts {get;set;}
   public Account theAccount {get;set;}   

   public String toSelect {get; set;}
   public String toUnselect {get; set;}
   public Decimal Total {get;set;}

   public Boolean overLimit {get;set;}

   private Opportunity_Contact_Role__c[] forDeletion = new Opportunity_Contact_Role__c[]{};


   public opportunityContactEntryExtension(ApexPages.StandardsetController controller) {

     Id opptyId = ApexPages.currentPage().getParameters().get('id');

     // Get information about the Opportunity being worked on
     theOpp = [select Id, AccountId, Account.Name from Opportunity where Id = :opptyId limit 1];

     // If products were previously selected need to put them in the "selected products" section to start with
     chosencontacts = [
        select Id, Contact__c, Contact_Name__c, Opportunity__c, Account_Manager_Notes__c, Date_Demo_Completed__c, 
            Delay_Followup_Until__c, Demo_Status__c, Demo_Time_zone__c, Demo_Tracked_On__c, PreDemo_Info_Quality__c, 
            Primary__c, Role__c, Sales_Scientist_Notes__c, Time_Demo_Requested__c 
        from Opportunity_Contact_Role__c 
        where Opportunity__c = :theOpp.Id];

     //show associated account
     theAccount = theOpp.Account;
     updateAvailableList();


   }

   // this is the 'action' method on the page
   public PageReference AccountCheck(){
   //if there is only one Account we go with it and save the opp
        if(theOpp.AccountId != theAccount.Id){
            try{
                theOpp.AccountId = theAccount.Id;
                update(theOpp);
            }
            catch(Exception e){
                ApexPages.addMessages(e);
            }
        }

        return null;

   }


      public void updateAvailableList() {

         // We dynamically build a query string and exclude items already in the shopping cart
         String qString = 'select Id, AccountId, name, firstname, lastname, email, phone from contact where AccountId = \'' + theAccount.Id + '\'';

         // note that we are looking for the search string entered by the user in the First Name OR Last Name
         // modify this to search other fields if desired
       if(searchString!=null){
         qString+= ' and (contact.FirstName like \'%' + searchString + '%\' or contact.LastName like \'%' + searchString + '%\')';
         }

         Set<Id> selectedEntries = new Set<Id>();
         for(Opportunity_Contact_Role__c d:chosencontacts){
            selectedEntries.add(d.contact__c);
         }

         if(selectedEntries.size()>0){
           String tempFilter = ' and Id not in (';
              for(Id i : selectedEntries){
                 tempFilter+= '\'' + (String)i + '\',';
              }
              String extraFilter = tempFilter.substring(0,tempFilter.length()-1);
              extraFilter+= ')';

              qString+= extraFilter;
         }

         qString+= ' order by Contact.Name';
         qString+= ' limit 101';

         system.debug('qString:' +qString);        
         availablecontacts = database.query(qString);

         // We only display up to 100 results... if there are more than we let the user know (see vf page)
         if(availablecontacts.size()==101){
            availablecontacts.remove(100);
            overLimit = true;
       }
       else{
           overLimit=false;
       }
    }

   public void addTochosencontacts(){

      // This function runs when a user hits "select" button next to a contact

      for(contact d : availablecontacts){
         if((String)d.Id==toSelect){
            chosencontacts.add(new Opportunity_Contact_Role__c(Opportunity__c=theOpp.Id, contact__c=d.id, role__c='Decision Maker'));
            break;
           }
       }

       updateAvailableList();  
   }


   public PageReference removeFromchosencontacts(){

       // This function runs when a user hits "remove" on an item in the "Chosen Contacts" section

       Integer count = 0;

       for(Opportunity_Contact_Role__c d : chosencontacts){
           if((String)d.contact__c==toUnselect){

               if(d.Id!=null)
                   forDeletion.add(d);

               chosencontacts.remove(count);
               break;
           }
           count++;
       }

       updateAvailableList();

       return null;
   }

   public PageReference onSave(){

       // If previously selected contacts are now removed, we need to delete them
       if(forDeletion.size()>0)
           delete(forDeletion);

       // Previously selected contacts may have new quantities and amounts, and we may have new products listed, so we use upsert here
       try{
          if(chosencontacts.size()>0)
             upsert(chosencontacts);
       }
       catch(Exception e){
          ApexPages.addMessages(e);
          return null;
       }  

       // After save return the user to the Opportunity
       return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
   }

   public PageReference onCancel(){

      // If user hits cancel we commit no changes and return them to the Opportunity   
      return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
   }


}

If anyone can help me that would be wonderful.

Thanks, Amanda

3

assuming that Opportunity_Contact_Role_c.Primary_c is Boolean, the following should do the trick

public PageReference onSave(){

// ...

if (chosencontacts.size() > 0)
{

    // go through choosenContacts and check if any has primary__c set to true
    Boolean primaryFound = false;
    for (Opportunity_Contact_Role__c ocr:chosencontacts)
    {
      if (ocr.Primary__c == true) {
        primaryFound = true;
        // exit loop here
        break;
      }
    }

    // if there's a primary upsert em
    if (isPrimaryFound){
        upsert(chosencontacts);
    }
    // otherwise shown an error
    else {

        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'YOUR ERROR MESSAGE HERE'));
        return null
    }
}


// ...

}
7
  • This should be correct but it kept giving me an error on the if(isPrimaryFound) line saying that variable isPrimaryFound does not exist. So I changed it to if(PrimaryFound = True) and that saved but now it will still let you save whether or not a contact is marked as primary. The Primary__c field is a checkbox so I don't understand why it's not working. – user2769 May 17 '13 at 19:24
  • can you please share the entire new code – Seb Wagner May 17 '13 at 20:57
  • The new code is at pastebin.com/atceDcKS – user2769 May 18 '13 at 2:53
  • Any idea why it is still not validating? – user2769 May 21 '13 at 15:27
  • add a debug statement and check what gets printed, because it should perform as expected, maybe some default value or something else if (ocr.Primary__c == true) { primaryFound = true; system.debug('###PRIMARY FOUND ' + ocr); } – Seb Wagner May 21 '13 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.