• KasiW
  • NEWBIE
  • 10 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 5
    Replies
Hello,

I have created a test class and trigger (see below).  The trigger works as expected but when I run the test I get the error:


Error MessageSystem.LimitException: Too many SOQL queries: 101
Stack TraceTrigger.d_Contract_Termination: line 30, column 1

 Woudl yo be able to help?   Thank you Kasia 

Trigger

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* {Purpose}
*
* @author   
* @version  
*/   
  
/**
* CHANGE HISTORY
* =============================================================================
* Date          Name                    Description
    Fixed bulk processing
* =============================================================================
*/
trigger d_Contract_Termination on Opportunity (before insert, after update)
    {   String firstname = UserInfo.getFirstName();
        String profile = UserInfo.getProfileId();
        boolean result = false;
        if (firstname != null && firstname.startsWith('-') == true && profile != null && profile == '00e30000001ion1AAA')
            {
               result = firstname.contains('d');               
            }
    if (result == false)
        {
            if (Trigger.isUpdate)
               
                {
                    //Prepare the booking map outside of the for loop to support bulk processing.
                    Map<String, List<GCRM_Booking_Period__c>> bookingMap = new Map<String, List<GCRM_Booking_Period__c>>();
                    for (GCRM_Booking_Period__c booking : [SELECT Id, Opportunity__c, Gcrm_Booking_Period__c, Booking_Value__c, Gcrm_Active_Booking__c 
                                    FROM GCRM_Booking_Period__c
                                   WHERE Opportunity__c = :Trigger.NewMap.keySet() AND Gcrm_Booking_Period__c > :date.today()]) {
                        List<GCRM_Booking_Period__c> innerList = bookingMap.get(booking.Opportunity__c);
                        if (innerList == null) {
                            innerList = new List<GCRM_Booking_Period__c>();
                            bookingMap.put(booking.Opportunity__c, innerList);
                        }                                       
                        innerList.add(booking);
                    }
                    

                    Map<Id,Opportunity> newOpportunityMap = Trigger.newMap;
                    Map<Id,Opportunity> oldOpportunityMap = Trigger.oldMap;
                    List<GCRM_Booking_Period__c> bookingsToUpdate = new List<GCRM_Booking_Period__c>();
                    
                    for(Id OpportunityId:newOpportunityMap.keySet())
                        {
                            Opportunity NewOpp = newOpportunityMap.get(opportunityId);
                            Opportunity OldOpp = oldOpportunityMap.get(opportunityId);        
                        
                            Date myDate = date.today();

// If a contract is not active yet, bookings will be recalculated if needed. So a user should not use the Actual Contract End Date but the Contract End Date.
                            
                            if (NewOpp.Actual_Contract_End_Date__c != null && (NewOpp.StageName != 'Closed Won' || NewOpp.Contract_Start_Date__c > myDate))
                                {
                                    NewOpp.addError('Actual Contract End Date can only be entered when Phase Line is Closed Won and the Contract is active.');
                                }

// When the contract is active and the Actual Contract End Date is set (for the first time), select all bookings with booking date past the Actual Contract End Date and render them inactive.
                            
                            else if (NewOpp.Actual_Contract_End_Date__c != null && OldOpp.Actual_Contract_End_Date__c == null)
                                {                                   
                                    List<GCRM_Booking_Period__c> bmap = bookingMap.get(opportunityId);
                                    if (bmap != null) {
                                        for (GCRM_Booking_Period__c booking : bmap) {
                                            if (booking.Gcrm_Booking_Period__c >= NewOpp.Actual_Contract_End_Date__c) {
                                                booking.Gcrm_Active_Booking__c = FALSE;
                                                bookingsToUpdate.add(booking);
                                            }
                                        }
                                    }
                                }                                                           
                            
// Once the Actual Contract End Date has been set, it can not be changed anymore.                            
                            
                            else if (NewOpp.Actual_Contract_End_Date__c <> OldOpp.Actual_Contract_End_Date__c && OldOpp.Actual_Contract_End_Date__c != null)
                                {
                                    NewOpp.addError('Actual Contract End Date cannot be changed.');
                                }
                        }
                        update bookingsToUpdate;  //keep this update outside of forloop to support bulk processing.
                }
            else

// In case an opportunity is created, it is not allowd to enter an Actual Contract End Date. Users should use the Contract End Date.

                {
                    for (Opportunity opp : Trigger.new)
                        {
                            if (opp.Actual_Contract_End_Date__c != null)
                                {
                                    opp.addError('Actual Contract End Date cannot be entered. Use the Contract End Date when creating an opportunity.');
                                }
                        }
                }
        }    
}

Test Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@isTest

private class TestTrigger3
//Test trigger in order to test Opportunity Trigger Actual_Close_Date
{

static testMethod void testOpportunityTrigger()
    {
       
        Account acct = new Account(name='Test Account', billingcountry = 'United States', billingstate ='CO');
        insert acct;
        Datetime myDate = Datetime.now();
        String dateOutput = myDate.format('yyyy-MM-dd');
    
        Opportunity opp = new Opportunity(AccountID=acct.Id,amount=300000, notice_period__c=4, name='test', CurrencyIsoCode='EUR', 
                   // CloseDate= Date.valueOf('2011-09-14'),StageName='Qualified',Contract_Start_Date__c= Date.valueOf('2011-10-01'),
                   // CloseDate= Date.valueOf(date.today().format('yyyy-MM-dd')),StageName='Qualified',Contract_Start_Date__c= Date.valueOf(date.today().format('yyyy-MM-dd')), 
                   CloseDate= Date.valueOf(dateOutput),StageName='Qualified',Contract_Start_Date__c= Date.valueOf(dateOutput), 
                    
                    Contract_Duration__c= 12,Billing_Type__c='SLA (includes all types)', Insurance_Coverage__c = 'Yes', Unusual_Insurance_Requirements__c = 'Yes', 
                    Warranty_Clause__c = 'Yes', Unusual_Damages__c = 'Yes', Risk_Do_Dont__c = 'Yes', Unusual_Risk__c = 'Yes', 
                    External_Counsel__c = 'Yes', Payment_Terms__c = 'Yes', Contract_Type__c='Staffing',Number_of_Positions__c=5);
        insert opp;
        
        opp.StageName='Closed Won';
        try
        {update opp;}
        catch(System.DMLException e)
        {
             System.assert(e.getMessage().contains('is'));
        }
        
        opp.StageName='Qualified';
        try
        {update opp;}
        catch(System.DMLException e)
        {
             System.assert(e.getMessage().contains('is'));
        }

        opp.StageName='Closed Won';    
        opp.name='test2';
        try
        {update opp;}
        catch(System.DMLException e)
        {
             System.assert(e.getMessage().contains('is'));
        }
        
    
        opp.StageName='Closed Won';
        opp.name='test3';
        try
        {update opp;}

        catch(System.DMLException e)
        {
             System.assert(e.getMessage().contains('Insertion failed'), 'message=' + e.getMessage());
             System.assert(e.getMessage().contains('phase'));
        }
    
        opp.Actual_Close_Date__c=Date.valueOf('2011-09-19');
        try
        {update opp;}

        catch(System.DMLException e)
        {
             System.assert(e.getMessage().contains('phase'));
        }

        Opportunity opp2 = new Opportunity(AccountID=acct.Id, name='test', CurrencyIsoCode='EUR', CloseDate= Date.valueOf('2011-09-14'),
        StageName='Qualified',Contract_Start_Date__c= Date.valueOf('2011-10-01'), Contract_Duration__c= 12, 
        Insurance_Coverage__c = 'Yes', Unusual_Insurance_Requirements__c = 'Yes', Warranty_Clause__c = 'Yes', Unusual_Damages__c = 'Yes', 
        Risk_Do_Dont__c = 'Yes', Unusual_Risk__c = 'Yes', Amount = 30, External_Counsel__c = 'Yes', Billing_Type__c = 'SLA (includes all types)', Payment_Terms__c = 'Yes', Contract_Type__c='Staffing',Number_of_Positions__c=5);
        insert opp2;
        
        opp2.StageName='Developed';
        try
        {update opp2;}
        
        catch(System.DMLException e)
        {
             System.assert(e.getMessage().contains('is'));
        }
    }
}
  • July 21, 2016
  • Like
  • 0
Hi, I wonder if you can help here> we have a custom renewal button that copies opportunity with certain data autopopulated along with products.  Now, we want to clone Contact Roles (primary as well)  when renewing/cloning opportunity. here is the code. would you be able how to modify it? Thank you in advance.  Kasia 

public class OpportunityRenewalController
{

    private ApexPages.StandardController controller {get; set;}
    private Opportunity opp {get;set;}
    public ID newRecordId {get;set;}
    public decimal num {get;set;}
    public date startDate {get;set;}
    public date endDate {get;set;}
    
    public OpportunityRenewalController(ApexPages.StandardController controller)
        {
            this.controller = controller;
            opp = (Opportunity)controller.getRecord();
        }
        
       
     public PageReference preCancel() {
       
          PageReference originalOpp = new ApexPages.StandardController(opp).view();
          originalOpp.setRedirect(true);
          return originalOpp;

    }
    public PageReference RenewalWithItems()
    {
        Savepoint sp = Database.setSavepoint();
        num = opp.Number_of_positions__c;
        //startDate = Opp.Contract_Start_Date__c;
        //endDate = Opp.Contract_End_Date__c;
        Opportunity newOpp;
         
        try
        {
            opp = [SELECT Id, AccountId, Account.Name, Name, Contract_Type__c, StageName, MarketRegion__c, 
                              Service_Offering__c, Market__c, Forecast_Status__c,Sub_Practice__c,
                              CurrencyIsoCode, Billing_Type__c, Service_Line__c, CampaignId, Campaign.Name, Amount,
                              Notice_Period__c, Delivery_Location__c, LeadSource, NextStep, Description, 
                              Insurance_Coverage__c, Unusual_Insurance_Requirements__c, Warranty_Clause__c, 
                              Unusual_Damages__c, Risk_Do_Dont__c, Unusual_Risk__c, External_Counsel__c, 
                              Payment_Terms__c, Gross_Margin__c, Authorized_Approver__c, Risk_Assessment_Comment__c, 
                              Contract_Start_Date__c, Contract_End_Date__c, Contract_Duration__c, 
                              CIBER_Opportunity_ID__c, Nearshore__c, Offshore__c, Onshore__c, 
                              Delivery_Location_Type_Poland_GSC__c,Solution_Set__c FROM Opportunity
                WHERE Id = :opp.Id];
            if (opp.StageName != 'Pre-Qualified')
            {
                 
                opp.StageName = 'Qualified';
                opp.Forecast_Status__c = 'Probable';                
                opp.Booking_Type__c = 'Existing Client - Renewals/Extension';                
                if ((opp.Contract_Start_Date__c != Null) &&  (opp.Contract_End_Date__c != Null))
                                {
                    opp.Contract_Start_Date__c = opp.Contract_End_Date__c.addDays(1);
                    integer iDuration = integer.valueOf(opp.Contract_Duration__c);
                    opp.Contract_End_Date__c = opp.Contract_Start_Date__c.addMonths(iDuration)-1;
                    opp.CloseDate = opp.Contract_Start_Date__c;
                    //opp.Number_of_Positions__c =opp.Number_of_Positions__c=5;
                    opp.Probability = 75;                   
                                       
                }
                       
           
                else
                {
                    opp.CloseDate = Date.today().addMonths(1);
                    //opp.Contract_Start_Date__c = Null;
                    //opp.Contract_End_Date__c = Null;
                    
                    integer iDuration = 0; 
                    opp.Probability = 75;                 
                }
                    
                     
                newOpp = opp.Clone(false);
                newOpp.Contract_Start_Date__c = startDate;
                newOpp.Contract_End_Date__c = endDate;
                if (opp.Contract_Type__c == 'Staffing') {
                    newOpp.Number_of_Positions__c = num;
                }
                
                
                insert newOpp;
                NewRecordId = newOpp.id;
                     
                List<OpportunityLineItem> items = new List<OpportunityLineItem>();
                for (OpportunityLineItem li : [Select l.Id, l.Quantity, l.Description, l.ServiceDate,l.UnitPrice, l.CurrencyIsoCode, l.PricebookEntryId, l.SortOrder, l.Cost_Price__c From OpportunityLineItem l where OpportunityId = :opp.id])
                {
                OpportunityLineItem newLI = li.clone(false);
                newLI.OpportunityId = newOpp.id;
                items.add(newLI);
                }
                insert items;
                     
                Note myNote = new Note (ParentId = newRecordId, Title = 'This is the renewal of CIBER Opportunity ID ' + opp.CIBER_Opportunity_ID__c);
                insert myNote;
            }
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Renewal not possible for opportunities with phase line Pre-Qualified'));
                return null;
            }
        }                            
            catch (Exception e)
            {
            Database.rollback(sp);
            ApexPages.addMessages(e);
            return null;
            }
  
           
           //PageReference oppPage = new ApexPages.standardcontroller(newOpp).view();
      PageReference oppPage = new ApexPages.StandardController(newOpp).edit();
        
       oppPage.setRedirect(true);

        if(newOpp != null)
         {
            return new PageReference ('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);
         }
         else
         {
             return null;
         }     
    }
    
  
}
  • May 16, 2016
  • Like
  • 0
Hi,  I have dowloaded an app from app exchange  - Opportunity Contact Roles Validation, 
https://appexchange.salesforce.com/listingDetail?listingId=a0N300000025Vs1EAE
Creates 2 custom fields on Opportunity: Number of Contacts and Primary Contact Assigned.
APEX trigger updates those fields every time before Opportunity is edited.

Create your own validation rules to restrict Sales from moving forward in the Sales Process (Defined Stage) if primary Contact Roles are not set. 


The class failed during the testing. line 39. Would you help please?  Thank you.
 
112
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class test_updatecontactrolecount
{
 public static testMethod void testcreateopptywithconditionandrole()
{
//Insert Opportunities 
try
{
    Opportunity Oppty = new Opportunity(Name='Oppty_test1',StageName='Defined', CloseDate=System.Today());
    insert Oppty;
    
    // insert contact
    Contact[] cont = new Contact[]
    {
        new Contact(LastName = 'testcontact1'),
        new Contact(LastName = 'testcontact2')
    };    
    insert cont;    
    // insert contact role     
    OpportunityContactRole [] ocr = new OpportunityContactRole[]
    {
    new OpportunityContactRole(Role ='Technical Buyer',OpportunityId=Oppty.id ,Contactid = cont[0].id ,Isprimary = True),
    new OpportunityContactRole(Role ='Technical Buyer',OpportunityId=Oppty.id ,Contactid = cont[1].id ,Isprimary = False)
    };
    insert ocr;    
    Oppty.StageName = 'Defined';    
    //Update opportunity
    
    Test.StartTest();
    update Oppty;
    Test.StopTest();
    
    Oppty =[SELECT Number_of_Contacts_Roles_Assigned__c,Primary_Contact_Assigned__c FROM Opportunity WHERE Id = :Oppty.Id];
    system.assert (Oppty.Number_of_Contacts_Roles_Assigned__c == 2);
    system.assert (Oppty.Primary_Contact_Assigned__c == True);
}
catch (System.DmlException e)
{
    System.assert(false);
}        

}

Here is the Trigger:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
11trigger updatecontactrolecount on Opportunity (before insert,before update)
{

Boolean isPrimary;
Integer iCount;

Map<String, Opportunity> oppty_con = new Map<String, Opportunity>();//check if the contact role is needed and add it to the oppty_con map
for (Integer i = 0; i < Trigger.new.size(); i++) 
{
        oppty_con.put(Trigger.new[i].id,
        Trigger.new[i]);      
}
isPrimary = False; 
for (List<OpportunityContactRole> oppcntctrle :[select OpportunityId from OpportunityContactRole where (OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId in :oppty_con.keySet())])
{
 if (oppcntctrle .Size() >0)
 {
 isPrimary = True;     
 }
}
iCount = 0;
for (List<OpportunityContactRole> oppcntctrle2 : [select OpportunityId from OpportunityContactRole where (OpportunityContactRole.OpportunityId in :oppty_con.keySet())])//Query for Contact Roles
{    
 if (oppcntctrle2 .Size()>0)
 {
 iCount= oppcntctrle2 .Size();     
 }
}
for (Opportunity Oppty : system.trigger.new) //Check if  roles exist in the map or contact role isn't required 
{
Oppty.Number_of_Contacts_Roles_Assigned__c = iCount;
Oppty.Primary_Contact_Assigned__c =isPrimary; 
}
  • April 13, 2016
  • Like
  • 0
hello, I have a VF page "Renew" button similar to standard clone button. It allows the user to perform what I call "quick edits" for a few key fields. When the opportunity  is opened by using Renawal button , the opportunity fields are displayed  in edit mode. If the users changes or adds to these fields, then clicks save, it does save the record as I want it to. However, instead of refreshing to display the VF page, the newly created (renewed) opportunity in View mode,  it refreshes to display the page layout of the Renewed (first) oportunity in Edit Mode. 

How can I see the new Renewed Opportunity in View Mode? Here  is my code. Please help. I appriciate any feedback.


public class OpportunityRenewalController
{

    private ApexPages.StandardController controller {get; set;}
    private Opportunity opp {get;set;}
    public ID newRecordId {get;set;}

    public OpportunityRenewalController(ApexPages.StandardController controller)
        {
            this.controller = controller;
            opp = (Opportunity)controller.getRecord();
        }
    
    public PageReference RenewalWithItems()
    {
        Savepoint sp = Database.setSavepoint();
        Opportunity newOpp;
         
        try
        {
            opp = [SELECT Id, AccountId, Account.Name, Name, Contract_Type__c, StageName, MarketRegion__c, Service_Offering__c, Market__c, Forecast_Status__c,Sub_Practice__c,CurrencyIsoCode, Billing_Type__c, Service_Line__c, CampaignId, Campaign.Name, Amount, Notice_Period__c, Delivery_Location__c, LeadSource, NextStep, Description, Insurance_Coverage__c, Unusual_Insurance_Requirements__c, Warranty_Clause__c, Unusual_Damages__c, Risk_Do_Dont__c, Unusual_Risk__c, External_Counsel__c, Payment_Terms__c, Gross_Margin__c, Authorized_Approver__c, Risk_Assessment_Comment__c, Contract_Start_Date__c, Contract_End_Date__c, Contract_Duration__c, CIBER_Opportunity_ID__c, Nearshore__c, Offshore__c, Onshore__c,Delivery_Location_Type_Poland_GSC__c,Solution_Set__c FROM Opportunity
                WHERE Id = :opp.Id];
            if (opp.StageName != 'Pre-Qualified')
            {
                 
                opp.StageName = 'Qualified';
                opp.Forecast_Status__c = 'Probable';                
                opp.Booking_Type__c = 'Existing Client - Renewals/Extension';                
                if ((opp.Contract_Start_Date__c != Null) &&  (opp.Contract_End_Date__c != Null))
                                {
                    opp.Contract_Start_Date__c = opp.Contract_End_Date__c.addDays(1);
                    integer iDuration = integer.valueOf(opp.Contract_Duration__c);
                    opp.Contract_End_Date__c = opp.Contract_Start_Date__c.addMonths(iDuration)-1;
                    opp.CloseDate = opp.Contract_Start_Date__c;
                    opp.Number_of_Positions__c =opp.Number_of_Positions__c=5;
                    opp.Probability = 75;                   
                                       
                }
                       
           
                else
                {
                    opp.CloseDate = Date.today().addMonths(1);
                    opp.Contract_Start_Date__c = Null;
                    opp.Contract_End_Date__c = Null;
                    integer iDuration = 0; 
                    opp.Probability = 75;                 
                }
                    
                     
                newOpp = opp.Clone(false);
                insert newOpp;
                     
                newRecordId = newOpp.id;
                     
                List<OpportunityLineItem> items = new List<OpportunityLineItem>();
                for (OpportunityLineItem li : [Select l.Id, l.Quantity, l.Description, l.ServiceDate,l.UnitPrice, l.CurrencyIsoCode, l.PricebookEntryId, l.SortOrder, l.Cost_Price__c From OpportunityLineItem l where OpportunityId = :opp.id])
                {
                OpportunityLineItem newLI = li.clone(false);
                newLI.OpportunityId = newOpp.id;
                items.add(newLI);
                }
                insert items;
                     
                Note myNote = new Note (ParentId = newRecordId, Title = 'This is the renewal of CIBER Opportunity ID ' + opp.CIBER_Opportunity_ID__c);
                insert myNote;
            }
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Renewal not possible for opportunities with phase line Pre-Qualified'));
                return null;
            }
        }                            
            catch (Exception e)
            {
            Database.rollback(sp);
            ApexPages.addMessages(e);
            return null;
            }
  
           //return new ApexPages.StandardController(newOpp).edit();
           //PageReference oppPage = new ApexPages.standardcontroller(newOpp).view();
        PageReference oppPage = new ApexPages.StandardController(newOpp).edit();
        //PageReference oppPage = new PageReference('/' + newOpp.id+'/e');
        //oppPage.setRedirect(true);


            //oppPage = new ApexPages.standardcontroller(newOpp).view();
            oppPage.setRedirect(true);
            return oppPage;
    }
}
  • May 27, 2015
  • Like
  • 0
Hi. I am trying to update the Forecast Category that is standard in SFDC when the % changes on my Oppty.  I am not able to reach the field with standard workflow so a field update will not work. Yet I cannot find resoleved question on this topic on the community forum. Any help would be much appriciated.

When the sales person changes probabaility % on the opportunity, the forecast category automatically updates:
Probability Forecast Category
10 Upside
20 Upside
30 Upside
40 Upside
50 Probable
60 Probable
70 Probable
80 Commit
90 Commit
100 Won
0 Omitted

thank you 
  • May 06, 2015
  • Like
  • 0
Hi,  I have dowloaded an app from app exchange  - Opportunity Contact Roles Validation, 
https://appexchange.salesforce.com/listingDetail?listingId=a0N300000025Vs1EAE
Creates 2 custom fields on Opportunity: Number of Contacts and Primary Contact Assigned.
APEX trigger updates those fields every time before Opportunity is edited.

Create your own validation rules to restrict Sales from moving forward in the Sales Process (Defined Stage) if primary Contact Roles are not set. 


The class failed during the testing. line 39. Would you help please?  Thank you.
 
112
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class test_updatecontactrolecount
{
 public static testMethod void testcreateopptywithconditionandrole()
{
//Insert Opportunities 
try
{
    Opportunity Oppty = new Opportunity(Name='Oppty_test1',StageName='Defined', CloseDate=System.Today());
    insert Oppty;
    
    // insert contact
    Contact[] cont = new Contact[]
    {
        new Contact(LastName = 'testcontact1'),
        new Contact(LastName = 'testcontact2')
    };    
    insert cont;    
    // insert contact role     
    OpportunityContactRole [] ocr = new OpportunityContactRole[]
    {
    new OpportunityContactRole(Role ='Technical Buyer',OpportunityId=Oppty.id ,Contactid = cont[0].id ,Isprimary = True),
    new OpportunityContactRole(Role ='Technical Buyer',OpportunityId=Oppty.id ,Contactid = cont[1].id ,Isprimary = False)
    };
    insert ocr;    
    Oppty.StageName = 'Defined';    
    //Update opportunity
    
    Test.StartTest();
    update Oppty;
    Test.StopTest();
    
    Oppty =[SELECT Number_of_Contacts_Roles_Assigned__c,Primary_Contact_Assigned__c FROM Opportunity WHERE Id = :Oppty.Id];
    system.assert (Oppty.Number_of_Contacts_Roles_Assigned__c == 2);
    system.assert (Oppty.Primary_Contact_Assigned__c == True);
}
catch (System.DmlException e)
{
    System.assert(false);
}        

}

Here is the Trigger:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
11trigger updatecontactrolecount on Opportunity (before insert,before update)
{

Boolean isPrimary;
Integer iCount;

Map<String, Opportunity> oppty_con = new Map<String, Opportunity>();//check if the contact role is needed and add it to the oppty_con map
for (Integer i = 0; i < Trigger.new.size(); i++) 
{
        oppty_con.put(Trigger.new[i].id,
        Trigger.new[i]);      
}
isPrimary = False; 
for (List<OpportunityContactRole> oppcntctrle :[select OpportunityId from OpportunityContactRole where (OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId in :oppty_con.keySet())])
{
 if (oppcntctrle .Size() >0)
 {
 isPrimary = True;     
 }
}
iCount = 0;
for (List<OpportunityContactRole> oppcntctrle2 : [select OpportunityId from OpportunityContactRole where (OpportunityContactRole.OpportunityId in :oppty_con.keySet())])//Query for Contact Roles
{    
 if (oppcntctrle2 .Size()>0)
 {
 iCount= oppcntctrle2 .Size();     
 }
}
for (Opportunity Oppty : system.trigger.new) //Check if  roles exist in the map or contact role isn't required 
{
Oppty.Number_of_Contacts_Roles_Assigned__c = iCount;
Oppty.Primary_Contact_Assigned__c =isPrimary; 
}
  • April 13, 2016
  • Like
  • 0
hello, I have a VF page "Renew" button similar to standard clone button. It allows the user to perform what I call "quick edits" for a few key fields. When the opportunity  is opened by using Renawal button , the opportunity fields are displayed  in edit mode. If the users changes or adds to these fields, then clicks save, it does save the record as I want it to. However, instead of refreshing to display the VF page, the newly created (renewed) opportunity in View mode,  it refreshes to display the page layout of the Renewed (first) oportunity in Edit Mode. 

How can I see the new Renewed Opportunity in View Mode? Here  is my code. Please help. I appriciate any feedback.


public class OpportunityRenewalController
{

    private ApexPages.StandardController controller {get; set;}
    private Opportunity opp {get;set;}
    public ID newRecordId {get;set;}

    public OpportunityRenewalController(ApexPages.StandardController controller)
        {
            this.controller = controller;
            opp = (Opportunity)controller.getRecord();
        }
    
    public PageReference RenewalWithItems()
    {
        Savepoint sp = Database.setSavepoint();
        Opportunity newOpp;
         
        try
        {
            opp = [SELECT Id, AccountId, Account.Name, Name, Contract_Type__c, StageName, MarketRegion__c, Service_Offering__c, Market__c, Forecast_Status__c,Sub_Practice__c,CurrencyIsoCode, Billing_Type__c, Service_Line__c, CampaignId, Campaign.Name, Amount, Notice_Period__c, Delivery_Location__c, LeadSource, NextStep, Description, Insurance_Coverage__c, Unusual_Insurance_Requirements__c, Warranty_Clause__c, Unusual_Damages__c, Risk_Do_Dont__c, Unusual_Risk__c, External_Counsel__c, Payment_Terms__c, Gross_Margin__c, Authorized_Approver__c, Risk_Assessment_Comment__c, Contract_Start_Date__c, Contract_End_Date__c, Contract_Duration__c, CIBER_Opportunity_ID__c, Nearshore__c, Offshore__c, Onshore__c,Delivery_Location_Type_Poland_GSC__c,Solution_Set__c FROM Opportunity
                WHERE Id = :opp.Id];
            if (opp.StageName != 'Pre-Qualified')
            {
                 
                opp.StageName = 'Qualified';
                opp.Forecast_Status__c = 'Probable';                
                opp.Booking_Type__c = 'Existing Client - Renewals/Extension';                
                if ((opp.Contract_Start_Date__c != Null) &&  (opp.Contract_End_Date__c != Null))
                                {
                    opp.Contract_Start_Date__c = opp.Contract_End_Date__c.addDays(1);
                    integer iDuration = integer.valueOf(opp.Contract_Duration__c);
                    opp.Contract_End_Date__c = opp.Contract_Start_Date__c.addMonths(iDuration)-1;
                    opp.CloseDate = opp.Contract_Start_Date__c;
                    opp.Number_of_Positions__c =opp.Number_of_Positions__c=5;
                    opp.Probability = 75;                   
                                       
                }
                       
           
                else
                {
                    opp.CloseDate = Date.today().addMonths(1);
                    opp.Contract_Start_Date__c = Null;
                    opp.Contract_End_Date__c = Null;
                    integer iDuration = 0; 
                    opp.Probability = 75;                 
                }
                    
                     
                newOpp = opp.Clone(false);
                insert newOpp;
                     
                newRecordId = newOpp.id;
                     
                List<OpportunityLineItem> items = new List<OpportunityLineItem>();
                for (OpportunityLineItem li : [Select l.Id, l.Quantity, l.Description, l.ServiceDate,l.UnitPrice, l.CurrencyIsoCode, l.PricebookEntryId, l.SortOrder, l.Cost_Price__c From OpportunityLineItem l where OpportunityId = :opp.id])
                {
                OpportunityLineItem newLI = li.clone(false);
                newLI.OpportunityId = newOpp.id;
                items.add(newLI);
                }
                insert items;
                     
                Note myNote = new Note (ParentId = newRecordId, Title = 'This is the renewal of CIBER Opportunity ID ' + opp.CIBER_Opportunity_ID__c);
                insert myNote;
            }
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Renewal not possible for opportunities with phase line Pre-Qualified'));
                return null;
            }
        }                            
            catch (Exception e)
            {
            Database.rollback(sp);
            ApexPages.addMessages(e);
            return null;
            }
  
           //return new ApexPages.StandardController(newOpp).edit();
           //PageReference oppPage = new ApexPages.standardcontroller(newOpp).view();
        PageReference oppPage = new ApexPages.StandardController(newOpp).edit();
        //PageReference oppPage = new PageReference('/' + newOpp.id+'/e');
        //oppPage.setRedirect(true);


            //oppPage = new ApexPages.standardcontroller(newOpp).view();
            oppPage.setRedirect(true);
            return oppPage;
    }
}
  • May 27, 2015
  • Like
  • 0

Hello Helpers

 

I have a requirement to inactivate an User right after creation  and send a notification  to the new User

This is not  aregular user bu t achatter free user who is invited to join a Group

 

The bussiness logic  is to deny  logging into the org  for Chatter free User  till they  perform some actions

 

I created a class contaning  a @future method  which  inactivates  an User  and send an email to that user

 

I call this future method  from within an after insert trigger on User object

 

The inactivation work always OK  but the mail is not always delivered.

I have no idea why  and I can not even debug

 

 

I can not  chech the debug  log  because the  user is not created manually by an admin but  by salesforce when chatter free user fill in the invitation form. 

 

any suggestion or a workaround?

 

thanks in advance

Csaba

 

 

 

 

  • June 28, 2013
  • Like
  • 0

Currently I am trying to update the Forecast Category that is standard in SFDC when the % changes on my Oppty.  I cannot seem to reach the field with standard workflow so a field update will not work.  Does anyone have any triggers that may be able to help with this issue?  I would hope it would run something like

 

If Probability is changed Forecast Category updates to x

 

I have an idea of how I want this to work but any additional help would be awesome!  All standard fields