• Will Jones 18
  • NEWBIE
  • 35 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 13
    Questions
  • 23
    Replies
Anyone have sample code for an account visualforce page that will hide a section based on a picklist value? This is for a contact manager edition so no apex is allowed. I would need this to be hidden on the edit page and the saved page of the account Thanks!
I'm looking to pass all contacts on an opportunity to an external system when an opp is saved/updated. The JSON format is below. What is the best way to achieve this?

Example output:
    [
        {
            "opportunity_contact_role_id":"",
            "contact_id":"",
            "role":"",
            "is_primary":""
        },
        {
            "opportunity_contact_role_id":"",
            "contact_id":"",
            "role":"",
            "is_primary":""
        }
    ]
I am attempting to do a call out to an external server to notify it to remove a contact from an opportunity if it is removed from the contact role on the opportunity in Salesforce. However the query I am attempting to use does not return any records. I attempted to delete a contact from an Opportunity and when I check by debug log I see that my query does not ever return any record. I trigger the opportunity successfully when the opportunitycontactrole is edited/deleted but it doesn't return the record. Any suggestion?
 
trigger OCR on Opportunity (after insert, after update, after delete) {

List<OpportunityContactRole> ocr_list_del = [SELECT Id, OpportunityId, ContactId, Role, IsPrimary FROM OpportunityContactRole WHERE OpportunityId IN: Trigger.newmap.keyset() AND IsDeleted=true ALL ROWS];

SYSTEM.DEBUG('The OCR Delete List Size is ' + ocr_list_del.size());

}

 
I need to update all the opportunities in my sandbox to test the bulk capability of sending the information to our custom portal via an HTTP Call Out.

Individually it works fine. However when I did a bulk update of 2800+ opportunities via DemandTools, only a hand full went over to our portal. My callout receives a set of IDs from a trigger (which is also bulkified I think). It should then process all of these IDs.

Anyone know if my trigger or callout is flawed or if it was a Salesforce limit hit?

Trigger
trigger CustomPortalOpp on Opportunity (after insert, after update) {
    
List<opportunity> oppList =  new List<opportunity>();

//prevents an infinite loop
if(Recursion.objectRecursion)
    return;
Recursion.objectRecursion = TRUE;

//Create list of opportunity
List<opportunity> opp_list = [SELECT Id, AccountId, Account_Manager_ID__c,  Client_Total__c, Event_Address__c,
                              Event_Consultant__c, Event_Date__c, Event_Start_Time__c, Event_End_Time__c,
                              Event_Status__c, Event_Type__c, Invite_Custom_Fields__c,
                              Invite_Headline__c, Invite_Request_Form__c, Invite_Yes_Limit__c,
                              Market__c, Name, Send_from_Email__c, Send_from_Name__c,
                              SG_Invite_ID__c, StageName, Time_Zone__c, Venue_Name__c FROM Opportunity WHERE Id IN: Trigger.newmap.keyset()];

   for (Opportunity o : opp_list) {
            opplist.add(o);
    }
    
    Set<Id> opptyIds = (new Map<Id,Opportunity>(oppList)).keySet();
    
    //process updates
    if (opp_list.isEmpty()==FALSE){
        
        if(!Test.isRunningTest()){
               IF(System.IsBatch() == false && System.isFuture() == false){ 
                    MySforceHttpCallOut.putDataToRemote_Opportunity(opptyIds); //call a method with @future annotation

               }

    }  
    
}
}


Apex Class - Call Out
public static void putDataToRemote_Opportunity(Set<Id> opptyIds){

String requestform;   
    
//Create list of opportunity
List<opportunity> opp_list = [SELECT Id, AccountId, Account_Manager_ID__c,  Client_Total__c, Event_Address__c,
                              Event_Consultant__c, Event_Date__c, Event_Start_Time__c, Event_End_Time__c,
                              Event_Status__c, Event_Type__c, Invite_Custom_Fields__c,
                              Invite_Headline__c, Invite_Request_Form__c, Invite_Yes_Limit__c,
                              Market__c, Name, Send_from_Email__c, Send_from_Name__c,
                              SG_Invite_ID__c, StageName, Time_Zone__c, Venue_Name__c 
                              FROM Opportunity WHERE Id IN: opptyIds];

   for (Opportunity o : opp_list) {
        String Stg = 'https://**********.com/api/v1/page2/' +o.Id+ '?token=123';
        String QA = 'https://**********.com/api/v1/page2/' +o.Id+ '?token=123';
        String PRD = 'https://**********.com/api/v1/page2/' +o.Id+ '?token=123';
             
             //Prepare https req
             httpRequest req = new httpRequest(); 
             req.setEndpoint(QA);
             //req.setHeader('X-HTTP-Method-Override', 'PATCH');
             req.setHeader('Content-Type','application/json');
             req.setMethod('PUT');
             req.setCompressed(false);
            
             if(o.Event_Start_Time__c == null)
                 o.Event_Start_Time__c = '';
             
             if(o.Invite_Custom_Fields__c == null)
                 o.Invite_Custom_Fields__c = '';
       
             if(o.Invite_Headline__c == null)
                 o.Invite_Headline__c = '';
       
            if(o.Invite_Yes_Limit__c == null)
                 o.Invite_Yes_Limit__c = 0;
       
             if(o.Send_From_Email__c == null)
                 o.Send_From_Email__c = '';
       
            if(o.Send_From_Name__c == null)
                 o.Send_From_Name__c = '';
       
            if(o.SG_Invite_ID__c == null)
                 o.SG_Invite_ID__c = '';
       
             if(o.Time_Zone__c == null)
                 o.Time_Zone__c = '';
       
            if(o.Venue_Name__c == null)
                 o.Venue_Name__c = '';
       
             if(o.Event_Address__c == null)
                 o.Event_Address__c = '';
       
            if(o.Event_Address__c == null)
                 o.Event_Address__c = '';
       
            requestForm = o.Invite_Request_Form__c;
       
            if(requestForm.contains('rsvp.stg.kapowevents.com')){
                requestForm = requestForm.replace('\"','\\"');
                SYSTEM.DEBUG(requestform);
            }
            else{
                requestForm = '';
                SYSTEM.DEBUG(requestform);
            }
                                                    

            

       
            //Build JSON String to send    
            String JSONString = '{\"Account_Manager_ID\":\"' + o.Account_Manager_ID__c +'\",\"Account_Id\":\"' + o.AccountId 
                +'\", \"Client_Total\":\"' + o.Client_Total__c +'\",\"event_consultant\":\"' 
                + o.event_consultant__c +'\",\"event_date\":\"' + o.event_date__c +'\",\"event_end_time\":\"' 
                + o.event_end_time__c +'\",\"event_start_time\":\"' 
                + o.event_start_time__c +'\",\"event_status\":\"' + o.event_status__c +'\",\"event_type\":\"' 
                + o.event_type__c +'\",\"opportunity_record_id\":\"' 
                + o.Id +'\",\"invite_custom_fields\":\"' + o.invite_custom_fields__c +'\",\"invite_headline\":\"' 
                + o.invite_headline__c +'\",\"invite_request_form\":\"' + requestform +'\",\"invite_yes_limit\":\"' 
                + o.invite_yes_limit__c +'\",\"market\":\"' + o.market__c +'\",\"name\":\"' 
                + o.name +'\",\"send_from_email\":\"' + o.send_from_email__c +'\",\"send_from_name\":\"' 
                + o.send_from_name__c +'\",\"sg_invite_id\":\"' + o.sg_invite_id__c +'\",\"stage_name\":\"' 
                + o.stagename +'\",\"time_zone\":\"' + o.time_zone__c +'\",\"venue_name\":\"' + o.venue_name__c +'\"}';
                                               
            System.debug('JSONString: ' + JSONString); //make sure format is correct
        
            
            req.setBody(JSONString);
     
            
            http http = new http();
            httpResponse res = http.send(req);
            
            System.debug(res.getBody());
            
        
  }

 
I am receiving the infamous "System.LimitException: Too many future calls: 51" based on a trigger in my contact object. I am not sure how to handle this as I thought I bulkifie my code and added the statement:

"IF(System.IsBatch() == false && System.isFuture() == false)"

What else could it be?
 
trigger PortalContact on Contact (after insert, after update) {

//prevents an infinite loop
if(Recursion.objectRecursion)
    return;
Recursion.objectRecursion = TRUE;

//Create list of contacts
List<contact> cont_list = [SELECT Id, Group_Name__c, FirstName, LastName, Email, Portal_Account__c FROM Contact WHERE Id IN: Trigger.newmap.keyset() AND Portal_Account__c = TRUE];

   for (Contact c : cont_list) {
       
       if(c.Portal_Account__c){  
       
           if(!Test.isRunningTest()){
               IF(System.IsBatch() == false && System.isFuture() == false){ 
                    MySforceHttpCallOut.putDataToRemote_Contact(c.id, c.Group_Name__c, c.FirstName, c.LastName, c.Email); //call a method with @future annotation
                    MySforceHttpCallOut.postDataToRemote_Contact(c.id, c.Group_Name__c, c.FirstName, c.LastName, c.Email);
               }
           }
       }
  }
    
    //process updates
    if (cont_list.isEmpty()==FALSE){
        database.update(cont_list);
    }  
    
}

 
How do I go about adding a a lookup field to a controller extension I have behind a visualforce page? Right now my lookup field is unable to do any searches. I can enter an actual record into the lookup field and it will save, BUT I cannot utilize the lookup search glass at all.
I have a visualforce page that is used to pull through attachments on the opportunity page. It is based off of the work Jeff Douglas did:

http://blog.jeffdouglas.com/2014/05/30/how-to-customize-salesforce-attachments/

The visualforce page and controller works fine but now I am having trouble adding a lookup field.

User-added image

The lookup field is based on a related list on the opportunity page. How do I add this field to the controller and page to make sure that a user can do a lookup and choose a "Vendor Event Details" that is associated with the current opportunity?

Controller:
 
public class UploadAttachmentController {
    
    public String contractType {get;set;}
    public String description {get;set;}
    String AttachmentId;
    public Attachment__c VED {get;set;}
    private Opportunity Opportunity {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    
    public UploadAttachmentController(ApexPages.StandardController controller) { 
        this.Opportunity = (Opportunity)controller.getRecord();
        
        VED = new Attachment__c();
        VED.Opportunity__c = this.Opportunity.Id;
  
            
    }   
    
    // creates a new Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Attachment__c obj = new Attachment__c();
        obj.Opportunity__c = Opportunity.Id;
        obj.description__c = description;
        obj.Contract_Type__c = contractType;
        obj.Vendor_Event_Detail__c = VED.Id;
        return Database.insert(obj);
        
    }
    
    // create an actual Attachment record with the 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;
        // insert the attachment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Attachment__c record
    *  2. Insert new Attachment with the new Attachment__c record as parent
    *  3. Update the 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
                Attachment__c customAttachment = [select id, Vendor_Event_Detail__c from Attachment__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                AttachmentId = customAttachmentResult.getId();           
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+AttachmentId);
    }
    
    public PageReference back() {
        return new PageReference('/'+Opportunity.Id);
    }     
 
}



Page:
 
<apex:page standardController="Opportunity" tabStyle="Opportunity" extensions="UploadAttachmentController">
 
 <apex:sectionHeader title="{!Opportunity.Name}" subtitle="Attach File"/>
 
 <apex:form id="form_Upload">
 <apex:pageBlock >
 
 <apex:pageBlockButtons >
   <apex:commandButton action="{!back}" value="Back to {!Opportunity.Name}"/>
   <apex:commandButton action="{!back}" value="Cancel"/>
 </apex:pageBlockButtons>
 <apex:pageMessages />
 
  <apex:pageBlockSection columns="1">
  
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File" for="file_File"/>
      <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Vendor Event Detail" for="VED"/>
      <apex:inputField id="VED" value="{!VED.Id}"/>
    </apex:pageBlockSectionItem>
   

    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Contract Type" for="contractType"/>
      <apex:selectList value="{!contractType}" size="1" id="type">
        <apex:selectOption itemvalue=""  itemLabel="--None--"/> 
        <apex:selectOption itemValue="Executed" itemLabel="Executed"/>
        <apex:selectOption itemValue="Final" itemLabel="Final"/>
      </apex:selectList>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Description" for="description"/> 
      <apex:inputTextarea id="description" value="{!description}" rows="4" cols="50"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="" for="uploadBtn"/> 
      <apex:commandButton id="uploadBtn" value="Attach File" action="{!processUpload}" />
    </apex:pageBlockSectionItem>    
    
  </apex:pageBlockSection>
 
 </apex:pageBlock>
 
 
 </apex:form>
 
</apex:page>


 
Users realized that a field was not being updated over the past few weeks. When debugging I realized that in my code the "Trigger.oldmap.get" is not working as it once was. The Trigger.oldmap.get returns the the latest commitment to the database, not the previous value as expected. Any clue why this code would stop working?
 
trigger UpdateSigningManger on Account (after insert, after update) {

//Updates Signing Manager field based on user profile and vendor stage


//prevents an infinite loop
if(Recursion2.objectRecursion)
    return;
Recursion2.objectRecursion = TRUE;

//get list of accounts
List<account> acct_list = [SELECT Id, Vendor_Stage__c, market__c, Signing_Manager_lookup__c, lastmodifiedbyid, lastmodifiedby.General_Manager__c,
createdbyid, createdby.General_Manager__c, lastmodifiedby.profile.name, createdby.profile.name, RecordTypeId FROM Account WHERE Id IN: Trigger.newmap.keyset()];
 
    
//get list of Venue markets and map them out
List <market__c> mkt_list = [SELECT Name, Venue_General_Manager__c FROM Market__c];
    
Map<string, string> mkt_map = new map<string, string>(); 
    
    for(Market__c mkt : mkt_list){
      mkt_map.put(mkt.Name, mkt.Venue_General_Manager__c);  
    }

for(Account acct : acct_list){

    
    if(Trigger.isUpdate && acct.RecordTypeId == '012C0000000M8xd'){
    
        // Initialize Boolean variables
        Boolean newAcctIsAgreed = FALSE;
        Boolean oldAcctIsAgreed = FALSE;
        
        //Access the old record by its ID in Trigger.oldmap
        Account oldAcct = Trigger.oldmap.get(acct.Id);
    
        //Trigger.new and Trigger.old values are assigned to boolean variables for comparison
        
        if(oldAcct.RecordTypeId == '012C0000000M8xd'){
            if(oldAcct.Vendor_Stage__c == null){
                oldAcctIsAgreed = FALSE;}
            else{
                oldAcctIsAgreed = oldAcct.Vendor_Stage__c.equals('Agreement of Commercials') || oldAcct.Vendor_Stage__c.equals('MSA Signed') || oldAcct.Vendor_Stage__c.equals('Covered by MSA');
            }
        }    
            if(acct.Vendor_Stage__c != null){
                newAcctIsAgreed = acct.Vendor_Stage__c.equals('Agreement of Commercials') || acct.Vendor_Stage__c.equals('MSA Signed') || Acct.Vendor_Stage__c.equals('Covered by MSA');
            }
        // Check that the field was just changed to the new value. 
         
        SYSTEM.DEBUG('Vendor Stage is ' + acct.Vendor_Stage__c);
        SYSTEM.DEBUG('oldAcctIsAgreed is ' + oldAcctIsAgreed);
        SYSTEM.DEBUG('newAcctIsAgreed is ' + newAcctIsAgreed); 
        
            if(!oldAcctIsAgreed && newAcctIsAgreed){
                if(acct.lastmodifiedby.profile.name.equals('Venue Manager') || acct.lastmodifiedby.profile.name.equals('Vendor Manager 2') ||acct.lastmodifiedby.profile.name.equals('C-Level') || acct.createdby.profile.name.equals('Coordinator') || acct.createdby.profile.name.equals('CSD') || acct.createdby.profile.name.equals('GM'))
                    {acct.Signing_Manager_lookup__c = acct.lastmodifiedbyid;
                    }
                else if(mkt_map.containsKey(acct.market__c))
                    {acct.Signing_Manager_lookup__c = mkt_map.get(acct.market__c);
                    }
                else if(acct.lastmodifiedby.General_Manager__c != null)
                    {acct.Signing_Manager_lookup__c = acct.lastmodifiedby.General_Manager__c;
                    }
                else{acct.Signing_Manager_lookup__c = acct.lastmodifiedbyid;
                    } 
            }
            
     }
            
     else {
         if(acct.RecordTypeId == '012C0000000M8xd'){
             if(acct.Vendor_Stage__c.equals('Agreement of Commercials') || acct.Vendor_Stage__c.equals('MSA Signed')|| acct.Vendor_Stage__c.equals('Covered by MSA'))
                 if(acct.createdby.profile.name.equals('Venue Manager') || acct.createdby.profile.name.equals('Vendor Manager 2') ||acct.createdby.profile.name.equals('C-Level') || acct.createdby.profile.name.equals('Coordinator') || acct.createdby.profile.name.equals('CSD') || acct.createdby.profile.name.equals('GM'))
                     {acct.Signing_Manager_lookup__c = acct.createdbyid;
                     }
                 else if(mkt_map.containsKey(acct.market__c))
                     {acct.Signing_Manager_lookup__c = mkt_map.get(acct.market__c);
                     } 
                 else if(acct.createdby.General_Manager__c != null)
                     {acct.Signing_Manager_lookup__c = acct.createdby.General_Manager__c;
                     }       
                 else {acct.Signing_Manager_lookup__c = acct.createdbyid;
                       }
         }
     }
    
  
}

if(acct_list.size()>0)
{
update acct_list;
}

}

 
I utilized Jeff Douglas' custom attachment code to create a custom object with a visualforce page.

http://blog.jeffdouglas.com/2014/05/30/how-to-customize-salesforce-attachments/

That worked fine. I added a lookup field to the attachment object. It is a lookup to a custom object that is filtered by the Opportunity ID.

User-added image

It works fine without the visualforce page. Now I need to add the lookup field to the custom controller and visualforce page. Users should be able to associate the attachment with the custom object as their creating the record from the visualforce page. I am having trouble adding it. I was able to add the field (Vendor Event Detail) but its read only and I cant do a lookup at all.

User-added image

Not sure where I should start with figuring out how to get the lookup icon to appear and make sure that the lookup is filtered by the opportunity it is associated with. Below is the code.

Visualforce Page:
 
<apex:page standardController="Opportunity" tabStyle="Opportunity" extensions="UploadAttachmentController">
 
 <apex:sectionHeader title="{!Opportunity.Name}" subtitle="Attach File"/>
 
 <apex:form id="form_Upload">
 <apex:pageBlock >
 
 <apex:pageBlockButtons >
   <apex:commandButton action="{!back}" value="Back to {!Opportunity.Name}"/>
   <apex:commandButton action="{!back}" value="Cancel"/>
 </apex:pageBlockButtons>
 <apex:pageMessages />
 
  <apex:pageBlockSection columns="1">
  
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File" for="file_File"/>
      <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Vendor Event Detail" for="VED"/>
      <apex:inputField id="VED" value="{!VED.Id}"/>
    </apex:pageBlockSectionItem>
   

    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Contract Type" for="contractType"/>
      <apex:selectList value="{!contractType}" size="1" id="type">
        <apex:selectOption itemvalue=""  itemLabel="--None--"/> 
        <apex:selectOption itemValue="Executed" itemLabel="Executed"/>
        <apex:selectOption itemValue="Final" itemLabel="Final"/>
      </apex:selectList>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Description" for="description"/> 
      <apex:inputTextarea id="description" value="{!description}" rows="4" cols="50"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="" for="uploadBtn"/> 
      <apex:commandButton id="uploadBtn" value="Attach File" action="{!processUpload}" />
    </apex:pageBlockSectionItem>    
    
  </apex:pageBlockSection>
 
 </apex:pageBlock>
 
 
 </apex:form>
 
</apex:page>



Controller:

 
public class UploadAttachmentController {
    
    public String contractType {get;set;}
    public String description {get;set;}
    String AttachmentId;
    public Attachment__c VED {get;set;}
    private Opportunity Opportunity {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    
    public UploadAttachmentController(ApexPages.StandardController controller) { 
        this.Opportunity = (Opportunity)controller.getRecord();
        
        VED = new Attachment__c();
        VED.Opportunity__c = this.Opportunity.Id;
  
            
    }   
    
    // creates a new Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Attachment__c obj = new Attachment__c();
        obj.Opportunity__c = Opportunity.Id;
        obj.description__c = description;
        obj.Contract_Type__c = contractType;
        obj.Vendor_Event_Detail__c = VED.Id;
        return Database.insert(obj);
        
    }
    
    // create an actual Attachment record with the 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;
        // insert the attachment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Attachment__c record
    *  2. Insert new Attachment with the new Attachment__c record as parent
    *  3. Update the 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
                Attachment__c customAttachment = [select id, Vendor_Event_Detail__c from Attachment__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                AttachmentId = customAttachmentResult.getId();           
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+AttachmentId);
    }
    
    public PageReference back() {
        return new PageReference('/'+Opportunity.Id);
    }     
 
}

 
For the past two days I've noticed that none of my apex class test are working in my sandbox. Whether I run all test or run them individually they do not work. No pass, no fail, just stays queued. I've tried clearing my test data, compiling the classes and everything but still no change. Anyone seen this and how did you solve the issue? My test work fine in my production instance.
I have the trigger below which updates a lookup field on our account page with a specific user depending on the criteria. It works when I test it in SF through the UI.
 
trigger UpdateSigningManger on Account (after insert, after update ) {

//If a Partnership person or GM, assign the Last Modified By user to Signing Manager when Vendor Stage
//goes to "Agreement of Commercials", "MSA Signed" or "Covered by MSA".
//Otherwise if not Partnership or C-Level, makes the signing manager the markets's GM.
//If the market's GM has not been assigned, assign to the user's GM.
//If all fails assign the current user.


//prevents an infinite loop
if(Recursion2.objectRecursion)
    return;
Recursion2.objectRecursion = TRUE;

List<account> acct_list = [SELECT Id, Vendor_Stage__c, market__c, Signing_Manager_lookup__c, lastmodifiedbyid, lastmodifiedby.General_Manager__c,
createdbyid, createdby.General_Manager__c, lastmodifiedby.profile.name, createdby.profile.name, RecordTypeId FROM Account WHERE Id IN: Trigger.newmap.keyset()];



for(Account acct : acct_list){

//query for the matching venue GM for that market 
string venue_gm = null;

list <market__c> venue_list = [SELECT Venue_General_Manager__c FROM Market__c WHERE Name =: acct.market__c];

if (venue_list.size()>0)
    {venue_gm =[SELECT Id, Name, Venue_General_Manager__c FROM Market__c WHERE Name =: acct.market__c LIMIT 1].Venue_General_Manager__c;}
    
    if(Trigger.isUpdate && acct.RecordTypeId == '012C0000000M8xd'){
    
        // Initialize Boolean variables
        Boolean newAcctIsAgreed = FALSE;
        Boolean oldAcctIsAgreed = FALSE;
        
        //Access the old record by its ID in Trigger.oldmap
        Account oldAcct = Trigger.oldmap.get(acct.Id);
    
        //Trigger.new and Trigger.old values are assigned to boolean variables for comparison
        
        if(oldAcct.RecordTypeId == '012C0000000M8xd'){
            if(oldAcct.Vendor_Stage__c == null){
                oldAcctIsAgreed = FALSE;}
            else{
                oldAcctIsAgreed = oldAcct.Vendor_Stage__c.equals('Agreement of Commercials') || oldAcct.Vendor_Stage__c.equals('MSA Signed') || oldAcct.Vendor_Stage__c.equals('Covered by MSA');
            }
        }    
            if(acct.Vendor_Stage__c != null){
                newAcctIsAgreed = acct.Vendor_Stage__c.equals('Agreement of Commercials') || acct.Vendor_Stage__c.equals('MSA Signed') || Acct.Vendor_Stage__c.equals('Covered by MSA');
            }
        // Check that the field was just changed to the new value.  
            if(!oldAcctIsAgreed && newAcctIsAgreed){
                if(acct.lastmodifiedby.profile.name.equals('Venue Manager') || acct.lastmodifiedby.profile.name.equals('Vendor Manager 2') ||acct.lastmodifiedby.profile.name.equals('C-Level'))
                    {acct.Signing_Manager_lookup__c = acct.lastmodifiedbyid;}
                else if(venue_gm != null)
                    {acct.Signing_Manager_lookup__c = venue_gm;}
                else if(acct.lastmodifiedby.General_Manager__c != null)
                    {acct.Signing_Manager_lookup__c = acct.lastmodifiedby.General_Manager__c;}
                else{acct.Signing_Manager_lookup__c = acct.lastmodifiedbyid;} 
            }
            
     }
            
     else {
         if(acct.RecordTypeId == '012C0000000M8xd'){
             if(acct.Vendor_Stage__c.equals('Agreement of Commercials') || acct.Vendor_Stage__c.equals('MSA Signed')|| acct.Vendor_Stage__c.equals('Covered by MSA'))
                 if(acct.createdby.profile.name.equals('Venue Manager') || acct.createdby.profile.name.equals('Vendor Manager 2') ||acct.createdby.profile.name.equals('C-Level'))
                     {acct.Signing_Manager_lookup__c = acct.createdbyid;}
                 else if(venue_gm != null)
                     {acct.Signing_Manager_lookup__c = venue_gm;} 
                 else if(acct.createdby.General_Manager__c != null)
                     {acct.Signing_Manager_lookup__c = acct.createdby.General_Manager__c;}       
                 else {acct.Signing_Manager_lookup__c = acct.createdbyid;}
         }
     }
    
  
}

if (acct_list.isEmpty()==FALSE){
    database.update(acct_list);
}

}

The test class below does not cover all cases yet, but I can't even get the first few test cases to work. Anywhere that I use the Signing Manager field in the assertion it is always null. I get the error "Assertion Failed: Expected: null, Actual: 'whatever the other value is' ". Why is my test class not populating the Signing Manager field but when I actually use the UI it works perfectly?
 
@isTest

private class Account_SigningManager_3 {

static testMethod void SigningManagerTest_3() {

Profile profilename = [select ID, name from Profile where Name = 'Account Manager' limit 1];

User u1 = new User();
      
       u1.FirstName = 'Nick';
       u1.LastName  = 'Jones';
       u1.Email     = 'nickjones+kapow@gmail.com';
       u1.Username  = 'nick-kapowtest1@gmail.com';
       u1.Alias     = 'auser';
       u1.ProfileId = profilename.ID;
       u1.TimeZoneSidKey    = 'America/Denver';
       u1.LocaleSidKey      = 'en_US';
       u1.EmailEncodingKey  = 'UTF-8';
       u1.LanguageLocaleKey = 'en_US';
       u1.isactive = TRUE;
       
       insert u1;
       

 Profile profilename2 = [select ID, name from Profile where Name = 'Venue Manager' limit 1];      
User u2 = new User();
       

       u2.FirstName = 'Anna';
       u2.LastName  = 'Smith';
       u2.Email     = 'annasmith+kapow@gmail.com';
       u2.Username  = 'sfdc-kapowtest2@gmail.com';
       u2.Alias     = 'buser';
       u2.ProfileId = profilename2.ID;
       u2.TimeZoneSidKey    = 'America/Denver';
       u2.LocaleSidKey      = 'en_US';
       u2.EmailEncodingKey  = 'UTF-8';
       u2.LanguageLocaleKey = 'en_US';
       u2.General_Manager__c = u1.id;
       u2.isactive = TRUE;
       insert u2;
       


       
User u3 = new User();
       

       u3.FirstName = 'Tim';
       u3.LastName  = 'West';
       u3.Email     = 'timwest+kapow@gmail.com';
       u3.Username  = 'sfdc-kapowtest3@gmail.com';
       u3.Alias     = 'cuser';
       u3.ProfileId = profilename2.ID;
       u3.TimeZoneSidKey    = 'America/Denver';
       u3.LocaleSidKey      = 'en_US';
       u3.EmailEncodingKey  = 'UTF-8';
       u3.LanguageLocaleKey = 'en_US';
       u3.General_Manager__c = u1.id;
       u3.isactive = TRUE;
       insert u3;
          

// Create Test Market
Market__c m1 = new Market__c(name='Dallas', Venue_General_Manager__c = u3.id );
insert m1;

// Create Test Market
Market__c m2 = new Market__c(name='Chicago', Venue_General_Manager__c = u2.id );
insert m2;




// Create Test Account
Account a1 = new Account(name='sample2', RecordTypeId = '012C0000000M8xd', Converted_From_Lead__c = TRUE, Vendor_Stage__c = 'One off event', Close_Date__c = date.Today(), Margin_Type__c = 'Standard', Target_Margin__c = 20, Vendor_Type__c = 'Activity', Website = 'www.test.com', market__c='Dallas');

// New Account 
insert a1; 


System.RunAs(u1){




//Test # 1 - update to MSA Signed, a Signing Manager stage


a1.Vendor_Stage__c = 'MSA Signed';
update a1;



Account result = [select createdbyId, lastmodifiedbyid, OwnerId, Signing_Manager_lookup__c, market__c, Vendor_Stage__c from Account where Id =: a1.Id limit 1]; 


system.debug('Stage is ' + result.Vendor_Stage__c);
system.debug('Market is ' + result.market__c);
system.debug('Venue Manager by ID is ' + u3.id);
system.debug('Created by ID is ' + result.createdbyId);
system.debug('Signing Manager by ID is ' + result.Signing_Manager_lookup__c);
system.debug('Owner by ID is ' + result.OwnerId);
System.assertEquals(m1.Venue_General_Manager__c, u3.id);
System.assertEquals(result.Signing_Manager_lookup__c, u3.id);


}

// Create Test Account
Account a2 = new Account(name='sample3', RecordTypeId = '012C0000000M8xd', Converted_From_Lead__c = TRUE, Vendor_Stage__c = 'One off event', Close_Date__c = date.Today(), Margin_Type__c = 'Standard', Target_Margin__c = 20, Vendor_Type__c = 'Activity', Website = 'www.test.com', market__c='Chicago');

// New Account 
insert a2; 


System.RunAs(u2){




//Test # 2 - update to MSA Signed, a Signing Manager stage


a2.Vendor_Stage__c = 'MSA Signed';
update a2;



Account result2 = [select createdbyId, lastmodifiedbyid, OwnerId, Signing_Manager_lookup__c, market__c, Vendor_Stage__c from Account where Id =: a2.Id limit 1]; 

system.debug('User 2 is ' + u2.id);
system.debug('User 2 is ' + result2.lastmodifiedbyid);
system.debug('Stage is ' + result2.Vendor_Stage__c);
system.debug('Market is ' + result2.market__c);
system.debug('Venue Manager by ID is ' + u3.id);
system.debug('Created by ID is ' + result2.createdbyId);
system.debug('Signing Manager by ID is ' + result2.Signing_Manager_lookup__c);
system.debug('Owner by ID is ' + result2.OwnerId);
System.assertEquals(m2.Venue_General_Manager__c, result2.lastmodifiedbyid); 
System.assertEquals(result2.Signing_Manager_lookup__c, result2.lastmodifiedbyid); 


}

System.RunAs(u2){    
// Create Test Account
Account a3 = new Account(name='sample4', RecordTypeId = '012C0000000M8xd', Converted_From_Lead__c = TRUE, Vendor_Stage__c = 'MSA Signed', Close_Date__c = date.Today(), Margin_Type__c = 'Standard', Target_Margin__c = 20, Vendor_Type__c = 'Activity', Website = 'www.test.com', market__c='Chicago');

// New Account 
insert a3; 







//Test # 3 - insert to MSA Signed, a Signing Manager stage






Account result3 = [select createdbyId, lastmodifiedbyid, OwnerId, Signing_Manager_lookup__c, market__c, Vendor_Stage__c from Account where Id =: a3.Id limit 1]; 

system.debug('User 2 is ' + u2.id);
system.debug('User 2 is ' + result3.lastmodifiedbyid);
system.debug('Stage is ' + result3.Vendor_Stage__c);
system.debug('Market is ' + result3.market__c);
system.debug('Venue Manager by ID is ' + u3.id);
system.debug('Created by ID is ' + result3.createdbyId);
system.debug('Signing Manager by ID is ' + result3.Signing_Manager_lookup__c);
system.debug('Owner by ID is ' + result3.OwnerId);
System.assertEquals(m2.Venue_General_Manager__c, result3.createdbyid); 



}




}

 
I am newer to writing triggers and I am not sure if the code below is causing me to receive the infamous Too Many DML Statements 151. Is it not bulkified correctly?

I took this code from what I saw online and just applied it to my situation. Essentially I needed to take the primary contact from my opportunity contact role and place it in a look field on the opportunity page so that I can look at it for workflows and such. Thanks in advance.
 
trigger InsertPrimaryContact on Opportunity (before insert, before update) {

Set<Id> OppIds = new Set<Id>();
for (Opportunity o : Trigger.new) {
    OppIds.add(o.id);}

Map<Id, List<OpportunityContactRole>> Opp_OCR = new Map<Id, List<OpportunityContactRole>>();

for (OpportunityContactRole oppocr : [select id, ContactId, Opportunityid, isPrimary from 
    OpportunityContactRole where opportunityid in :OppIds and isPrimary = true]) {

    List<OpportunityContactRole> tmp_oppocr = new List<OpportunityContactRole>();

    tmp_oppocr = Opp_OCR.get(oppocr.opportunityid);

    if (tmp_oppocr == null) {
        Opp_OCR.put(oppocr.opportunityid, new List<OpportunityContactRole>{oppocr});
    } 
    
    else {

        tmp_oppocr.add(oppocr);
        Opp_OCR.put(oppocr.opportunityid, tmp_oppocr);
    }
} 




system.debug('Final Opp_OCR map: '+Opp_OCR);


for (Opportunity opps : Trigger.new) {
    List<OpportunityContactRole> this_oppocr = new List<OpportunityContactRole>();
    this_oppocr = Opp_OCR.get(opps.id);
    system.debug('this Opps ('+opps.id+') list of oppocrs: '+this_oppocr);

    if (this_oppocr == null) {
        opps.Primary_Contact__c = null;
    }    
    else {

        for (OpportunityContactRole r : this_oppocr) {
            if (r.isprimary) 
                opps.Primary_Contact__c = r.ContactId;
        } 
    } 
} 

}



 
I have a controller that I built based off this article:

http://www.soliantconsulting.com/blog/2012/08/view-triggers-salesforce-trigger-opportunity-contact-roles

However the issues is after I add a contact role and return to the opportunity page, the fields are not updated. It only updates when I do a manual page refresh.

Here is my controller:
 
public without sharing class OppHelper {
    public Opportunity opp;
    public OppHelper( ApexPages.StandardController stdController ) {
        opp = ( Opportunity )stdController.getRecord();        
    }
    public void insertOppContacts(){
        OppHelper.insertOppContactsFuture( opp.Id );    
    }
    @future public static void insertOppContactsFuture( Id oppId ) {
        Contact[] contactList = [ SELECT Id, FirstName, LastName, Email FROM Contact
                             WHERE Id IN ( SELECT ContactId FROM OpportunityContactRole
                                         WHERE OpportunityId = :oppId AND isPrimary = True ) ];
        Opportunity opp = [ SELECT Id, Primary_Contact__c FROM Opportunity WHERE Id = :oppId ];
        
        for( Contact contact : contactList ) {
            opp.Primary_Contact__c = contact.Id;
        }
        update opp;
    }
}



Here is my visualforce page:
 
<apex:page standardController="Opportunity" extensions="OppHelper" action="{!insertOppContacts}" />

 
Anyone have sample code for an account visualforce page that will hide a section based on a picklist value? This is for a contact manager edition so no apex is allowed. I would need this to be hidden on the edit page and the saved page of the account Thanks!
I am receiving the infamous "System.LimitException: Too many future calls: 51" based on a trigger in my contact object. I am not sure how to handle this as I thought I bulkifie my code and added the statement:

"IF(System.IsBatch() == false && System.isFuture() == false)"

What else could it be?
 
trigger PortalContact on Contact (after insert, after update) {

//prevents an infinite loop
if(Recursion.objectRecursion)
    return;
Recursion.objectRecursion = TRUE;

//Create list of contacts
List<contact> cont_list = [SELECT Id, Group_Name__c, FirstName, LastName, Email, Portal_Account__c FROM Contact WHERE Id IN: Trigger.newmap.keyset() AND Portal_Account__c = TRUE];

   for (Contact c : cont_list) {
       
       if(c.Portal_Account__c){  
       
           if(!Test.isRunningTest()){
               IF(System.IsBatch() == false && System.isFuture() == false){ 
                    MySforceHttpCallOut.putDataToRemote_Contact(c.id, c.Group_Name__c, c.FirstName, c.LastName, c.Email); //call a method with @future annotation
                    MySforceHttpCallOut.postDataToRemote_Contact(c.id, c.Group_Name__c, c.FirstName, c.LastName, c.Email);
               }
           }
       }
  }
    
    //process updates
    if (cont_list.isEmpty()==FALSE){
        database.update(cont_list);
    }  
    
}

 
How do I go about adding a a lookup field to a controller extension I have behind a visualforce page? Right now my lookup field is unable to do any searches. I can enter an actual record into the lookup field and it will save, BUT I cannot utilize the lookup search glass at all.
I have a visualforce page that is used to pull through attachments on the opportunity page. It is based off of the work Jeff Douglas did:

http://blog.jeffdouglas.com/2014/05/30/how-to-customize-salesforce-attachments/

The visualforce page and controller works fine but now I am having trouble adding a lookup field.

User-added image

The lookup field is based on a related list on the opportunity page. How do I add this field to the controller and page to make sure that a user can do a lookup and choose a "Vendor Event Details" that is associated with the current opportunity?

Controller:
 
public class UploadAttachmentController {
    
    public String contractType {get;set;}
    public String description {get;set;}
    String AttachmentId;
    public Attachment__c VED {get;set;}
    private Opportunity Opportunity {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    
    public UploadAttachmentController(ApexPages.StandardController controller) { 
        this.Opportunity = (Opportunity)controller.getRecord();
        
        VED = new Attachment__c();
        VED.Opportunity__c = this.Opportunity.Id;
  
            
    }   
    
    // creates a new Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Attachment__c obj = new Attachment__c();
        obj.Opportunity__c = Opportunity.Id;
        obj.description__c = description;
        obj.Contract_Type__c = contractType;
        obj.Vendor_Event_Detail__c = VED.Id;
        return Database.insert(obj);
        
    }
    
    // create an actual Attachment record with the 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;
        // insert the attachment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Attachment__c record
    *  2. Insert new Attachment with the new Attachment__c record as parent
    *  3. Update the 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
                Attachment__c customAttachment = [select id, Vendor_Event_Detail__c from Attachment__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                AttachmentId = customAttachmentResult.getId();           
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+AttachmentId);
    }
    
    public PageReference back() {
        return new PageReference('/'+Opportunity.Id);
    }     
 
}



Page:
 
<apex:page standardController="Opportunity" tabStyle="Opportunity" extensions="UploadAttachmentController">
 
 <apex:sectionHeader title="{!Opportunity.Name}" subtitle="Attach File"/>
 
 <apex:form id="form_Upload">
 <apex:pageBlock >
 
 <apex:pageBlockButtons >
   <apex:commandButton action="{!back}" value="Back to {!Opportunity.Name}"/>
   <apex:commandButton action="{!back}" value="Cancel"/>
 </apex:pageBlockButtons>
 <apex:pageMessages />
 
  <apex:pageBlockSection columns="1">
  
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File" for="file_File"/>
      <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Vendor Event Detail" for="VED"/>
      <apex:inputField id="VED" value="{!VED.Id}"/>
    </apex:pageBlockSectionItem>
   

    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Contract Type" for="contractType"/>
      <apex:selectList value="{!contractType}" size="1" id="type">
        <apex:selectOption itemvalue=""  itemLabel="--None--"/> 
        <apex:selectOption itemValue="Executed" itemLabel="Executed"/>
        <apex:selectOption itemValue="Final" itemLabel="Final"/>
      </apex:selectList>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Description" for="description"/> 
      <apex:inputTextarea id="description" value="{!description}" rows="4" cols="50"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="" for="uploadBtn"/> 
      <apex:commandButton id="uploadBtn" value="Attach File" action="{!processUpload}" />
    </apex:pageBlockSectionItem>    
    
  </apex:pageBlockSection>
 
 </apex:pageBlock>
 
 
 </apex:form>
 
</apex:page>


 
Users realized that a field was not being updated over the past few weeks. When debugging I realized that in my code the "Trigger.oldmap.get" is not working as it once was. The Trigger.oldmap.get returns the the latest commitment to the database, not the previous value as expected. Any clue why this code would stop working?
 
trigger UpdateSigningManger on Account (after insert, after update) {

//Updates Signing Manager field based on user profile and vendor stage


//prevents an infinite loop
if(Recursion2.objectRecursion)
    return;
Recursion2.objectRecursion = TRUE;

//get list of accounts
List<account> acct_list = [SELECT Id, Vendor_Stage__c, market__c, Signing_Manager_lookup__c, lastmodifiedbyid, lastmodifiedby.General_Manager__c,
createdbyid, createdby.General_Manager__c, lastmodifiedby.profile.name, createdby.profile.name, RecordTypeId FROM Account WHERE Id IN: Trigger.newmap.keyset()];
 
    
//get list of Venue markets and map them out
List <market__c> mkt_list = [SELECT Name, Venue_General_Manager__c FROM Market__c];
    
Map<string, string> mkt_map = new map<string, string>(); 
    
    for(Market__c mkt : mkt_list){
      mkt_map.put(mkt.Name, mkt.Venue_General_Manager__c);  
    }

for(Account acct : acct_list){

    
    if(Trigger.isUpdate && acct.RecordTypeId == '012C0000000M8xd'){
    
        // Initialize Boolean variables
        Boolean newAcctIsAgreed = FALSE;
        Boolean oldAcctIsAgreed = FALSE;
        
        //Access the old record by its ID in Trigger.oldmap
        Account oldAcct = Trigger.oldmap.get(acct.Id);
    
        //Trigger.new and Trigger.old values are assigned to boolean variables for comparison
        
        if(oldAcct.RecordTypeId == '012C0000000M8xd'){
            if(oldAcct.Vendor_Stage__c == null){
                oldAcctIsAgreed = FALSE;}
            else{
                oldAcctIsAgreed = oldAcct.Vendor_Stage__c.equals('Agreement of Commercials') || oldAcct.Vendor_Stage__c.equals('MSA Signed') || oldAcct.Vendor_Stage__c.equals('Covered by MSA');
            }
        }    
            if(acct.Vendor_Stage__c != null){
                newAcctIsAgreed = acct.Vendor_Stage__c.equals('Agreement of Commercials') || acct.Vendor_Stage__c.equals('MSA Signed') || Acct.Vendor_Stage__c.equals('Covered by MSA');
            }
        // Check that the field was just changed to the new value. 
         
        SYSTEM.DEBUG('Vendor Stage is ' + acct.Vendor_Stage__c);
        SYSTEM.DEBUG('oldAcctIsAgreed is ' + oldAcctIsAgreed);
        SYSTEM.DEBUG('newAcctIsAgreed is ' + newAcctIsAgreed); 
        
            if(!oldAcctIsAgreed && newAcctIsAgreed){
                if(acct.lastmodifiedby.profile.name.equals('Venue Manager') || acct.lastmodifiedby.profile.name.equals('Vendor Manager 2') ||acct.lastmodifiedby.profile.name.equals('C-Level') || acct.createdby.profile.name.equals('Coordinator') || acct.createdby.profile.name.equals('CSD') || acct.createdby.profile.name.equals('GM'))
                    {acct.Signing_Manager_lookup__c = acct.lastmodifiedbyid;
                    }
                else if(mkt_map.containsKey(acct.market__c))
                    {acct.Signing_Manager_lookup__c = mkt_map.get(acct.market__c);
                    }
                else if(acct.lastmodifiedby.General_Manager__c != null)
                    {acct.Signing_Manager_lookup__c = acct.lastmodifiedby.General_Manager__c;
                    }
                else{acct.Signing_Manager_lookup__c = acct.lastmodifiedbyid;
                    } 
            }
            
     }
            
     else {
         if(acct.RecordTypeId == '012C0000000M8xd'){
             if(acct.Vendor_Stage__c.equals('Agreement of Commercials') || acct.Vendor_Stage__c.equals('MSA Signed')|| acct.Vendor_Stage__c.equals('Covered by MSA'))
                 if(acct.createdby.profile.name.equals('Venue Manager') || acct.createdby.profile.name.equals('Vendor Manager 2') ||acct.createdby.profile.name.equals('C-Level') || acct.createdby.profile.name.equals('Coordinator') || acct.createdby.profile.name.equals('CSD') || acct.createdby.profile.name.equals('GM'))
                     {acct.Signing_Manager_lookup__c = acct.createdbyid;
                     }
                 else if(mkt_map.containsKey(acct.market__c))
                     {acct.Signing_Manager_lookup__c = mkt_map.get(acct.market__c);
                     } 
                 else if(acct.createdby.General_Manager__c != null)
                     {acct.Signing_Manager_lookup__c = acct.createdby.General_Manager__c;
                     }       
                 else {acct.Signing_Manager_lookup__c = acct.createdbyid;
                       }
         }
     }
    
  
}

if(acct_list.size()>0)
{
update acct_list;
}

}

 
For the past two days I've noticed that none of my apex class test are working in my sandbox. Whether I run all test or run them individually they do not work. No pass, no fail, just stays queued. I've tried clearing my test data, compiling the classes and everything but still no change. Anyone seen this and how did you solve the issue? My test work fine in my production instance.
I am newer to writing triggers and I am not sure if the code below is causing me to receive the infamous Too Many DML Statements 151. Is it not bulkified correctly?

I took this code from what I saw online and just applied it to my situation. Essentially I needed to take the primary contact from my opportunity contact role and place it in a look field on the opportunity page so that I can look at it for workflows and such. Thanks in advance.
 
trigger InsertPrimaryContact on Opportunity (before insert, before update) {

Set<Id> OppIds = new Set<Id>();
for (Opportunity o : Trigger.new) {
    OppIds.add(o.id);}

Map<Id, List<OpportunityContactRole>> Opp_OCR = new Map<Id, List<OpportunityContactRole>>();

for (OpportunityContactRole oppocr : [select id, ContactId, Opportunityid, isPrimary from 
    OpportunityContactRole where opportunityid in :OppIds and isPrimary = true]) {

    List<OpportunityContactRole> tmp_oppocr = new List<OpportunityContactRole>();

    tmp_oppocr = Opp_OCR.get(oppocr.opportunityid);

    if (tmp_oppocr == null) {
        Opp_OCR.put(oppocr.opportunityid, new List<OpportunityContactRole>{oppocr});
    } 
    
    else {

        tmp_oppocr.add(oppocr);
        Opp_OCR.put(oppocr.opportunityid, tmp_oppocr);
    }
} 




system.debug('Final Opp_OCR map: '+Opp_OCR);


for (Opportunity opps : Trigger.new) {
    List<OpportunityContactRole> this_oppocr = new List<OpportunityContactRole>();
    this_oppocr = Opp_OCR.get(opps.id);
    system.debug('this Opps ('+opps.id+') list of oppocrs: '+this_oppocr);

    if (this_oppocr == null) {
        opps.Primary_Contact__c = null;
    }    
    else {

        for (OpportunityContactRole r : this_oppocr) {
            if (r.isprimary) 
                opps.Primary_Contact__c = r.ContactId;
        } 
    } 
} 

}



 

Hi and thanks for reading this and for any help...

 

The requirement is to stop users from saving duplicate Team Member roles when they add or edit their Default Opportunity or Account Team.  

 

So, if Tom wants to add users to his default opp team, he can only add 1 "Sales Manager", 1 "Sales Lead", etc.

 

 

Eric

 

Hi,

I have a formula field named Contract End Date and the value of this field should be calucated based on Contract Start Date and the Contract Duration. Contract Start Date is of type Date and Contract Duration is the number of months. Id I just add both the fields it considers Contract Duration as number of days instead of month. How do I achieve this?

Thanks
Jina