• 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());
       
      }
 
}



 
I have a custom object called Project, and a subordinate custom object called CRM Hour Tracker, what i would like to do is create a scheduled Apex Class to create a new CRM Hour Tracker every month on the first day of that month for every Project in the system.(Only About 110). I know how to do the scheduling of the Apex Class, my problem is i need each of these CRM Hour Trackers to relate to a different Project. Anyone have any ideas?
I am creating a trigger that display the Last Completed Call date on the Account. I have the following code
 
trigger LastCompletedCallDate on Task (after insert, after update, after 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(createdDate)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=aggregateResult.get('MaxCDate')));
          
     }
      
     try{
      
         if(acc_list !=null && acc_list.size()>0){
             update acc_list;
         }
      
     }Catch(Exception e){
         system.debug('Exception ***'+e.getMessage());
       
      }
 
}

And I'm receiving this error: Compile Error: Invalid field initializer: Date.Last_Completed_Call__c at line 25 column 72
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?
 
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.
I have an Apex Trigger listed below, I need to change where it says Subject = 'Email Sent' or Subject = 'Email Received' to be Subject Contains Email, but I can seem to get it to work properly.
 
trigger SumEmailActivitesOnAccount on Task (after insert, after update, after delete) {

    set<Id> set_Id = new set<Id>();
   
    List<Account>acc_list = new List<Account>();
    
    if(Trigger.isInsert || Trigger.isUpdate) {
        for(Task T:Trigger.new){
            set_Id.add(T.WhatId);
        }

     }
    else if(Trigger.isDelete){
        for(Task T:Trigger.old){
            set_Id.add(T.WhatId);
        }

     }
     
    if(Trigger.isAfter && (Trigger.isUpdate || Trigger.isInsert || Trigger.isDelete)){
        acc_list=[SELECT Id, Sum_Email_Activities__c, (SELECT Id FROM Tasks WHERE Status = 'Completed' AND (Subject = 'Email Sent' or Subject = 'Email Received')) FROM Account WHERE Id IN :set_Id];

     for(Account acc: acc_list){
        if(acc.Tasks.size()>0)
            acc.Sum_Email_Activities__c = acc.Tasks.size();
        else
            acc.Sum_Email_Activities__c = 0;
     }
        if(!acc_list.isEmpty())
            update acc_list;
        }

}

 
Okay so I have a Trigger that fires after insert of Task. The Trigger works perfectly, I wrote the following Test Class and I'm only getting 75% code Coverage and I need more than that because my org average is only at 57%. Any help would be greatly appreciated.
 
@isTest

public class TestTaskCreationAccount {

    static testMethod void insertNewTask() {
    
        Task taskToCreate = new Task();
        
        taskToCreate.OwnerId = '005i0000004N77x';
        taskToCreate.Subject = 'Attempted Call';
        taskToCreate.Status = 'Completed';
        
        insert taskToCreate;
        
        taskToCreate = [SELECT Status From Task WHERE Id =:taskToCreate.Id];
        System.debug('Status after trigger fired: ' + taskToCreate.Status);
        
        System.assertEquals('Completed', taskToCreate.Status);
        
        delete taskToCreate;
        
    }
    
    
}

 
I have an Apex Trigger losted below. It counts the number of tasks on an account, and it works perfectly, but i want it to only count Attempted and Completed Call, I currently have it counting only Attempted Calls because everytime i try and add Completed Call it doesnt work at all. Any Ideas?

trigger SumCallActivitesOnAccount on Task (after insert, after update, after delete) {

    set<Id> set_Id = new set<Id>();
   
    List<Account>acc_list = new List<Account>();
    
    if(Trigger.isInsert || Trigger.isUpdate) {
        for(Task T:Trigger.new){
            set_Id.add(T.WhatId);
        }

     }
    else if(Trigger.isDelete){
        for(Task T:Trigger.old){
            set_Id.add(T.WhatId);
        }

     }
     
    if(Trigger.isAfter && (Trigger.isUpdate || Trigger.isInsert || Trigger.isDelete)){
        acc_list=[SELECT Id, Sum_Call_Activities__c, (SELECT Id FROM Tasks WHERE Subject = 'Attempted Call') FROM Account WHERE Id IN :set_Id];

     for(Account acc: acc_list){
        if(acc.Tasks.size()>0)
            acc.Sum_Call_Activities__c = acc.Tasks.size();
        else
            acc.Sum_Call_Activities__c = 0;
     }
        if(!acc_list.isEmpty())
            update acc_list;
        }

}
I have an Apex Trigger that I am creating that is to count the number of Tasks that are on an Account, the code is listed below.
 
trigger SumTotalActivitesOnAccount on Task (after insert, after update, after delete) {

    set<Id> set_Id = new set<Id>();
    
    List<Account>acc_list = new List<Account>();
    
    if(Trigger.isInsert || Trigger.isUpdate) {
        for(Task T:trigger.new){
            set_Id.add(T.What);
        }
        
    }
    else if(Trigger.isDelete){
        for(Task T:Trigger.old){
            set_Id.add(T.What);
        }
        
    }
    
    if(Trigger.isAfter && (Trigger.isUpdate || Trigger.isInsert || Trigger.isDelete)){
        acc_list=[SELECT Id, Sum_Total_Activities__c, (SELECT Id, FROM Tasks) FROM Account WHERE Id IN :set_Id];
    
    for(Account acc: acc_list){
        if(acc.Tasks.size()>0)
            acc.Sum_Total_Activities__c = acc.Tasks.size();
        else
            acc.Sum_Total_Activities__c = 0;
    }
     if(!acc_list.isEmpty())
            update acc_list;
  }

}

I keep getting an error that states: Compile Error: unexpected token: 'FROM' at line 21 column 66

Any help would be greatly appreciated.
So I have a custom object called Airport which is a lookup to the Account object, and it literally is just all of the Airports in America. And what i would like to do is create a formula field on the Account that Displays the closest Airport to that address. Does anyone know how this is possible? I would like to be able to just compare them by city and state.

So for instance lets say that the account is for Quicken Loans Arena in Ohio, then I want it to take Cleveland, Ohio and find the airport that is the closest to that location which would be Cleveland-Hopkins International. I can explain this alittle better if I'm not being clear enough.

Any Ideas?
I am trying to create a Formula Field that displays the name of the nearest Airport to the Account's Billing address.

I was handed this task about a week ago, and have triede everything that I can think of and have researched it thouroughly and have come up dry. I am really hoping that one of you lovely developers on here will have some advice for me as to how i should attempt to accomplish this task.
I have an Apex Trigger listed below:
 
trigger ActiveAssignedBDMsTrigger on Assigned_BDM__c (after insert, after update, after delete) { 
    set<Id> set_id = new set<Id>();
    
    List<Project__c>prj_list = new List<Project__c>();
    
    if(trigger.isInsert || trigger.isUpdate) {
        for(Assigned_BDM__c bdm: trigger.new) {
            set_id.add(bdm.CampaignX__c);
        }
    }
    else if(trigger.isDelete) {
        for(Assigned_BDM__c bdm: trigger.old) {
            set_id.add(bdm.CampaignX__c);
        }
    }
    
    if(trigger.isAfter && (trigger.isUpdate || trigger.isInsert || trigger.isDelete)) {
        prj_list = [SELECT id, Number_Of_Active_BDMs__c, (SELECT id,name FROM Assigned_BDMs1__r WHERE Active__c = TRUE) FROM Project__c WHERE id IN :set_id];
        
        for(Project__c prj: prj_list) {
            if(prj.Assigned_BDMs1__r.size() > 0) 
                prj.Number_Of_Active_BDMs__c = prj.Assigned_BDMs1__r.size();
            else
                prj.Number_Of_Active_BDMs__c = 0;
        }
        if(!prj_list.isEmpty())
            update prj_list;
    }
}

And I am trying to write a test class for it to get full code coverage, because my production org is currently at 70% so i need to bring the average up.

Can anyone give me any ideas?
I'm trying to create a test class that is going to create a new "Assigned_BDM__c" and I keep getting this error: Compile Error: Illegal assignment from String to Date at line 12 column 5.

Here is my test class:
 
@isTest

public class TestActiveBDMsTriggerOnInsert {

    static testMethod void insertNewBDM() {
    
    Assigned_BDM__c bdmToCreate = new Assigned_BDM__c();
    
    bdmToCreate.BDM_Assigned1__c = 'a0Ki0000009XKgM';
    bdmToCreate.CampaignX__c = 'a0Ei000000Y24Jh';
    bdmToCreate.Account_Name__c = '001i000000box1d';
    bdmToCreate.Start_Date__c = '1/28/2015';
    
    insert bdmToCreate;
    
    }
    
}

Any help would be greatly appreciated.
I have an Apex Trigger that counts the number of Projects that have been created on an Account, and i realized today that if you create the first Project on an Account the field displays 1, but then if you delete that Project the field still displays 1. I need it to go back to zero if there are no Projects on the Account anymore.

Any help would be greatly appreciated,
I have an Apex Trigger listed below, what it does is it shows a count of how many Projects are linked to an Account, it works perfectly but I added a checkbox to the Project object and I would like to now only count Projects that have that checkbox checked. Can anyone help me with this?
 
trigger RollupActiveProjectsCountToAccountTrigger on Project__c (after insert, after delete, after undelete) {

   List<Id>AccountIds = new List<Id>();    
   
   If(Trigger.isInsert || Trigger.isUndelete){
       for(Project__c p: Trigger.new){
           AccountIds.add(p.Company_Name__c);
       }
   }
   
   If(Trigger.isDelete){
       for(Project__c p: Trigger.old){
               AccountIds.add(p.Company_Name__c);
       }
   }
   
   AggregateResult[] groupedResults = [SELECT count(id)projectCount, Company_Name__c FROM Project__c WHERE Company_Name__c in :AccountIds GROUP BY Company_Name__C];
   
   Map<Id,Account>accountMap = new Map<Id,Account>([SELECT Id, Total_Active_Projects__c FROM Account WHERE Id in :AccountIds]);
   
   for(AggregateResult ar: groupedresults) {
       accountMap.get((Id)ar.get('Company_Name__c')).Total_Active_Projects__c = (decimal)ar.get('Projectcount');
   }
   
   try {
       update accountMap.values();
   } catch(DmlException e) {
       System.debug(e.getMessage());
   }

}

 
I have a custom object called "Project" that looks up to the object "Account" and I would like to create a Trigger that simply tells me how many "Projects" are linked to that specific "Account". Im just looking for someone to point me in the right direction.

Any help would be greatly appreciated.
I am kind of new to writing validation rules and I'm trying to write one for if the field "BillingState" = "OH" then the field "Industry must be populated. Any help would be greatly appreciated.
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?
 
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??
  • February 19, 2015
  • Like
  • 0
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