• Chad Moutes
  • NEWBIE
  • 120 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 20
    Questions
  • 58
    Replies
Hey all,

I have created the following Apex trigger that will create, update and delete Opportunity Contact Roles based on a Contact Lookup field placed on the Opportunity. Everything works great currently. I am just trying to figure out one final scenario. If John Doe already has a Contact Role but is not the Primary Contact Role and I want him to be. I want to be able to change my look up field to him and then have that check him as the primary. Currently it just creates a new one and checks them both as primary. So what I need to do is check the current Contact Roles and if there is already one with the same name as in the Lookup field then just check that one as primary, but if there isn't then create a new one. Below is the code. Please let me know if you need further description.

Thanks,
 
trigger CreateContactRole on Opportunity (after insert, after update) {
    
    List<OpportunityContactRole> newContactRoleList = new List<OpportunityContactRole>();
    List<OpportunityContactRole> oldContactRoleList = new List<OpportunityContactRole>();
    Set<Id> OppId = new Set<Id>();
    sET<Id> ContactId = new Set<Id>();
    
    if(Trigger.isInsert) {
        for(Opportunity opp : Trigger.new) {
          if(opp.Primary_Contact__c != null) {
              //Creating new Contact Role
              newContactRoleList.add(new OpportunityContactRole(ContactId=opp.Primary_Contact__c,OpportunityId=opp.Id,Role='Decision Maker',IsPrimary=true));
          }
      }
    }
    
    if(Trigger.isUpdate) {      
      for(Opportunity opp : Trigger.new) {
          if(opp.Primary_Contact__c != null && Trigger.oldMap.get(opp.Id).Primary_Contact__c == null) {
                //Creating new Contact Role
              newContactRoleList.add(new OpportunityContactRole(ContactId=opp.Primary_Contact__c,OpportunityId=opp.Id,Role='Decision Maker',IsPrimary=true));
          }
            else if(opp.Primary_Contact__c != null && Trigger.oldMap.get(opp.Id).Primary_Contact__c != null) {
                //Create New Contact Role make new CR Primary over the old CR
                Opportunity OldOpp = Trigger.oldMap.get(opp.Id);
                OppId.add(OldOpp.id);
                ContactId.add(OldOpp.Primary_Contact__c);
                newContactRoleList.add(new OpportunityContactRole(ContactId=opp.Primary_Contact__c,OpportunityId=opp.Id,Role='Decision Maker',IsPrimary=true));
            }
          else if(opp.Primary_Contact__c == null && Trigger.oldMap.get(opp.Id).Primary_Contact__c != null) {
                Opportunity OldOpp = Trigger.oldMap.get(opp.Id);
                OppId.add(OldOpp.id);
                ContactId.add(OldOpp.Primary_Contact__c);
                try {
                //Deleting old Contact Roles
                if(oldContactRoleList.size()>0) delete oldContactRoleList;
                }
                catch(Exception e) {
                    System.debug(e);
                    trigger.new[0].addError('An error has occurred. Please contact your system administrator.');
                }
          }
      }
    }
    
    try {
        //inserting new contact roles
        if(newContactRoleList.size()>0)insert newContactRoleList;
        
        //Selecting old Contact Roles
        if(OppId.size()>0) oldContactRoleList = [Select Id from OpportunityContactRole where ContactId in : ContactId and OpportunityId in : OppId];        
        
    }
    catch(Exception e) {
        System.debug(e);
        trigger.new[0].addError('An error has occurred. Please contact your system administrator.');
    }
}


 
Hello All,

I am trying to delete an Apex Class, and its associated Test Class from my production instance. I am changing the status to Deleted and then doing the deploy to server from Force.com IDE. But it is failing due to code coverage issues, but the only class/trigger that is less than 75% CC is the class that I am trying to delete. Am I missing something?

Any and all help would be greatly appreciated.
I was trying to deploy some code this morning from sandbox to production, and I received this error on a test class that was written by someone else at my company. They copied it from somewhere online and have no idea what this error is. I am curious if someone can help me figure out what is wrong with this test class that is causing the following error: 


System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow. A flow trigger failed to execute the flow with version ID 301310000008shZ. Contact your administrator for help.: [] 
Stack Trace: Class.MyProfilePageControllerTest.testSave: line 34, column 1

Here is the full test class:
 
/**
 * An apex class that keeps updates of a portal user in sync with its corresponding contact.
   Guest users are never able to access this page.
 */
@IsTest public with sharing class MyProfilePageControllerTest {
    @IsTest(SeeAllData=true) static void testSetContactFields() {
        User u = [select title, firstname, lastname, email, phone, mobilephone, fax, street, city, state, postalcode, country
                           FROM User WHERE id =: UserInfo.getUserId()];

        Contact c = new Contact();

        MyProfilePageController.setContactFields(c, u);
        System.assertEquals(c.firstname, u.firstname, 'firstname should have been set as the firstname of the user for the contact');
        System.assertEquals(c.lastname, u.lastname, 'lastname should have been set as the lastname of the user for the contact');
    }

    @IsTest(SeeAllData=true) static void testSave() {
        // Modify the test to query for a portal user that exists in your org
        List<User> existingPortalUsers = [SELECT id, profileId, userRoleId FROM User WHERE UserRoleId <> null AND UserType='CustomerSuccess'];

        if (existingPortalUsers.isEmpty()) {
            User currentUser = [select id, title, firstname, lastname, email, phone, mobilephone, fax, street, city, state, postalcode, country
                                FROM User WHERE id =: UserInfo.getUserId()];
            MyProfilePageController controller = new MyProfilePageController();
            System.assertEquals(currentUser.Id, controller.getUser().Id, 'Did not successfully load the current user');
            System.assert(controller.getIsEdit() == false, 'isEdit should default to false');
            controller.edit();
            System.assert(controller.getIsEdit() == true);
            controller.cancel();
            System.assert(controller.getIsEdit() == false);

            Contact c = new Contact();
            c.LastName = 'TestContact';
            insert c;

            c.title = currentUser.title;
            c.firstname = currentUser.firstname;
            c.lastname = currentUser.lastname;
            c.email = currentUser.email;
            c.phone = currentUser.phone;
            c.mobilephone = currentUser.mobilephone;
            c.fax = currentUser.fax;
            c.mailingstreet = currentUser.street;
            c.mailingcity = currentUser.city;
            c.mailingstate = currentUser.state;
            c.mailingpostalcode = currentUser.postalcode;
            c.mailingcountry = currentUser.country;
            controller.save();
            System.assert(Page.ChangePassword.getUrl().equals(controller.changePassword().getUrl()));
        } else {
            User existingPortalUser = existingPortalUsers[0];
            String randFax = Math.rint(Math.random() * 1000) + '5551234';

            System.runAs(existingPortalUser) {
                MyProfilePageController controller = new MyProfilePageController();
                System.assertEquals(existingPortalUser.Id, controller.getUser().Id, 'Did not successfully load the current user');
                System.assert(controller.getIsEdit() == false, 'isEdit should default to false');
                controller.edit();
                System.assert(controller.getIsEdit() == true);

                controller.cancel();
                System.assert(controller.getIsEdit() == false);

                controller.getUser().Fax = randFax;
                controller.save();
                System.assert(controller.getIsEdit() == false);
            }

            // verify that the user and contact were updated
            existingPortalUser = [Select id, fax, Contact.Fax from User where id =: existingPortalUser.Id];
            System.assert(existingPortalUser.fax == randFax);
            System.assert(existingPortalUser.Contact.fax == randFax);
        }
    }
}

Any and all help will be greatly appreciated.
I have an Apex Trigger that takes the list of Tasks that meet a certain criteria and finds the one with the Max Date and then populates a field on the Account with that date. The trigger works great, but I would like it so that if the list size = 0 then the field will return to null. Currently the previous value will just stay in there. Any help would be greatly appreciated.
 
trigger LastCompletedCallDate on Task (after insert, after update, before delete) { 
     
    Set<Id> acc_set = new Set<Id>();
     
    List<Account> acc_list = new List<Account>();
     
    if(trigger.isInsert || trigger.isUpdate){
    for(Task T: Trigger.new){
        if(String.valueof(T.WhatId).startsWith('001') && T.Status=='Completed' && T.Subject=='Completed Call' ){
            acc_set.add(T.WhatId);
        }
         
     }
     }
     if(trigger.isDelete){
        for(Task T: Trigger.old){
        if(String.valueof(T.WhatId).startsWith('001') && T.Status=='Completed' && T.Subject=='Completed Call' ){
            acc_set.add(T.WhatId);
        }
         
     }
     }
      
     for(AggregateResult aggregateResult:[SELECT max(Due_Date__c)MaxCDate,WhatId FROM Task WHERE WhatID IN: acc_set AND Status ='Completed' AND Subject ='Completed Call' Group By WhatId]){
         acc_list.add(new Account(Id=(id)aggregateResult.get('WhatId'),Last_Completed_Call__c=(date)aggregateResult.get('MaxCDate')));
         
          
     }
      
     try{
      
         for(Account acc: acc_List){
         if(acc_list.size()>0)
             update acc_list;
         else
             acc.Last_Completed_Call__c = null;
         }
      
     }Catch(Exception e){
         system.debug('Exception ***'+e.getMessage());
       
      }
 
}



 
Hello!

I would like to add a condition to my controller so that only records that match a certain field value will be evalueted... but I can not get the syntax correct.  Here is what I currently have: 
 
[Select id, name, Call_Volume_This_Week__c, Spend_Last_Week__c, Week_to_Date_SpendFRM__c, Record_Scope__c from Buyer_Performance__c]

And I would like it to function as: 

[Select id, name, Call_Volume_This_Week__c, Spend_Last_Week__c, Week_to_Date_SpendFRM__c, Record_Scope__c from Buyer_Performance__c WHERE Record_Scope__c = "YES"]

How would I properly execute this?

Thanks, 

John
I have an Apex Trigger that is currenty calling upon a MAX function to display the most recent date a Task has been created.
 
for(AggregateResult aggregateResult:[SELECT max(createdDate)MaxCDate,WhatId FROM Task WHERE WhatID IN: acc_set AND Status ='Completed' AND Subject ='Completed Call' Group By WhatId]){
I want to change the date field that it is referencing from createdDate to ActivityDate like below:
 
for(AggregateResult aggregateResult:[SELECT max(ActivityDate)MaxCDate,WhatId FROM Task WHERE WhatID IN: acc_set AND Status ='Completed' AND Subject ='Completed Call' Group By WhatId]){

But when I do I recieve the following error: field ActivityDate does not support aggregate operator MAX at line 26 column 42.

Can anyone help me out here?
 
what is inner class and outer class??
Hello,

I would like to write an Apex Trigger on the Task Object that will populate a date field on the Account Object with the Created Date of the Last Activity With a Status of Completed and a Subject of Completed Call.

Anyone have any ideas on how to approach this.

Hi,

 

I have a custom field on the opportunity object named 'contact__c'. This is a simple lookup field.

If populated I want a trigger that creates an Opportunity contact role for that same contact.

 

Any ideas?

 

I can update the contact__c field based on the primary contact role but I need this work the other way round.

 

Any ideas?

 

Thanks