• George Adams
  • NEWBIE
  • 160 Points
  • Member since 2016

  • Chatter
    Feed
  • 3
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 35
    Replies
Hello, 

I need to make my trigger fire only when the case description is not null. is this the right way to approach this? I've really new to APEX and it's really throwing me for a loop. 

trigger descUpdate on Case (before update) {    
    case[] cases = Trigger.new;
    if(case.description !=null)
    caseDescUpdate.descUpdate(cases);
}

Thanks!

-Mike

Hi,

I'm new to Salesforce and I'm struggling since a few hours on how to bulkify this trigger.

I have an object called kognoz1__Invoice2__c linked with an opportunity through a lookup field. This object has 3 email custom fields :"Relance_Email__c","Relance_CC_Email__c" and "Relance__CC2_Email__c".

The trigger must copy the emails from the Contact Role of the Opportunity linked with my custom object in those 3 previous email fields. But only when the roles of the contacts are :"Decisionnaire et Comptabilité" or "Comptabilité" and moreover when a checkbox named  "Relance_Automatique" ( which is a custom field on the contact object ) is checked. 

The fact is that an opportunity can have one, two or three contact role corresponding to the conditions that's why I'm using three email custom fields in the kognoz1__Invoice2__c object.

Here is the trigger i made, it is working fine when I'm updating the kognoz records one by one but I would like to use a Batch in order to update a lot of records and I'm getting a "too many SOQL queries Error". 

 

trigger UpdateContactEmailRelance on kognoz1__Invoice2__c (before insert, before update) {
        for(kognoz1__Invoice2__c k : trigger.new){
        List<OpportunityContactRole> Contactsearch = [Select ContactId from OpportunityContactRole where OpportunityId=:k.kognoz1__Opportunity__c and (Role='Décisionnaire et Comptabilité' or Role='Comptabilité')];
        if(Contactsearch.size()==1){
            k.Relance_CC_Email__c='';
            k.Relance_CC2_Email__c='';
            Contact email1=[Select Email, Relance_Automatique__c from Contact where Id=:Contactsearch[0].ContactId];
            if(email1.Relance_Automatique__c=true){
                k.Relance_Email__c=email1.Email;
            }
            else k.Relance_Email__c='';
        }
        if(Contactsearch.size()==2){
            k.Relance_CC2_Email__c='';
            List<Contact> emails=[Select Email, Relance_Automatique__c from Contact where (Id=:Contactsearch[0].ContactId or Id=:Contactsearch[1].ContactId) and Relance_Automatique__c=true];
            if(emails.size()==1){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c='';
            }
            else if(emails.size()==2){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c=emails[1].Email;
            }
            else{
                k.Relance_Email__c='';
                k.Relance_CC_Email__c='';
            }
        }
        if(Contactsearch.size()==3){
            List<Contact> emails=[Select Email, Relance_Automatique__c from Contact where (Id=:Contactsearch[0].ContactId or Id=:Contactsearch[1].ContactId or Id=:Contactsearch[2].ContactId) and Relance_Automatique__c=true];
            if(emails.size()==1){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c='';
                k.Relance_CC2_Email__c='';
            }
            else if(emails.size()==2){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c=emails[1].Email;
                k.Relance_CC2_Email__c='';
            }
            else if(emails.size()==3){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c=emails[1].Email;
                k.Relance_CC2_Email__c=emails[2].Email;
            }
            else{
                k.Relance_Email__c='';
                k.Relance_CC_Email__c='';
                k.Relance_CC2_Email__c='';
            }
        }
    }
}


I know that I must bulkify it but I can't figure out how to do it. 

Thank you in advance !

I wrote a small trigger to populate a lookup field on the Opportunity object, and I can't seem to get my test class to enter the loop which contains the assignment of this field. The query appears to have all the necessary info, I'm not sure what's wrong.
Here is the trigger: 
 

trigger FillPrimaryPartner on Opportunity (before insert, before update) {
    for (Opportunity opp : trigger.new){
        for (Partner p : [select id from Partner where IsPrimary=true and AccountFromId =: opp.AccountId]){
            opp.Primary_Partner__c = p.Id; 
        }
    }
}
and here is its test class:
@isTest
public class TESTFillPrimaryPartner {
	static testMethod void insertNewData(){
        
        Account partAcct = new Account();
        partAcct.Type = 'Signed Partner';
        partAcct.Industry = 'Retail';
        partAcct.BillingCountry = 'Italy';
        insert partAcct;
        
        Account oppAcct = new Account();
        oppAcct.Type = 'Customer';
        oppAcct.Industry = 'CPG';
        oppAcct.BillingCountry = 'Italy';
        insert oppAcct;
        
        Opportunity opp1 = new Opportunity();
        Opportunity.AccountId = oppAcct.Id;
        insert opp1;
        
        Partner part1 = new Partner();
        part1.IsPrimary = true;
        part1.AccountFromId = oppAcct.Id;
        part1.AccountToId = partAcct.Id;
        insert part1;
    }
}


 
Hello,

I can't get this code to work. I keep getting the response, "{"Code":50,"Message":"Must supply a valid HTTP Basic Authorization header"}".

I'm trying to get data from Campaign Monitor, as shown here.

Here is the code I'm using:
Http httpProtocol = new Http();
HttpRequest request = new HttpRequest();
request.setEndPoint('https://api.createsend.com/api/v3.1/clients.json');


Blob headerValue = Blob.valueOf('u:' + '34534j5hk34j5hk34j5hk3j45hk3j'); //not my actual API key :)
String authorizationHeader = EncodingUtil.base64Encode(headerValue);
request.setHeader('Authorization', 'Basic ' + authorizationHeader);

//I've also tried it like this:
request.setHeader('Authorization', authorizationHeader);

request.setMethod('GET');
HttpResponse response = httpProtocol.send(request);
System.debug(response.getBody());

Are my headers missing info? I can't firgure out what it's looking for.

Thanks!
I'm very new to VF and Apex. I'm plotting a list of values on a time-series chart, but am having trouble handling the dynamic nature of the number/names of the multiple series on the x-axis of the plot.

Here is the controller:
public class BarChartController {
    // Return a list of data points for a chart
    public List<Data> getData() {
        return BarChartController.getChartData();
    }
    
    // Make the chart data available via JavaScript remoting
    @RemoteAction
    public static List<Data> getRemoteData() {
        return BarChartController.getChartData();
    }
    
    // The actual chart data; needs to be static to be
    // called by a @RemoteAction method
    public static List<Data> getChartData() {
        List<Data> data = new List<Data>();
        List<CM_Group_Tracking__c> allData = new List<CM_Group_Tracking__c>([SELECT Id, Action__c, Email__c, DateTime__c, Group__c
                                                                             FROM CM_Group_Tracking__c
                                                                             ORDER BY DateTime__c ASC NULLS LAST]);
        Set<String> groupNamesSet = new Set<String>();
        List<String> last30days = new List<String>();
        Map<String, Map<String, Integer>> groupNamesMap = new Map<String, Map<String, Integer>>();
        
        //create set of all existing group names
        for (CM_Group_Tracking__c st : allData) {
            try {
                groupNamesSet.add(st.Group__c);
            } catch (Exception e) {
                system.debug('%%% exception adding group name to set: ' + e);
            }
        }
        
        //loop through last 30 days (including today) as i
        for (Integer i = 30; i >0; i--) {
            last30days.add(string.valueOf(datetime.now().addDays(-i).format('MMM-d')));
            //setup map for holding values
            for (String s : groupNamesSet) {
                Map<String,Integer> tmpMap = New Map<String,Integer>();
                groupNamesMap.put(string.valueOf(datetime.now().addDays(-i).format('MMM-d')), tmpMap);
                groupNamesMap.get(string.valueOf(datetime.now().addDays(-i).format('MMM-d'))).put(s, 0);
            }
            
        }
                
        //add each stat to the correct map and submap
        for (CM_Group_Tracking__c st : allData) {
            
            //format and get date of current stat
            string statDay;
            if (st.DateTime__c != null) {statDay = st.DateTime__c.format('MMM-d');}            
            
            boolean hasTimeAndAction = st.DateTime__c != null && st.Action__c != null;
            
            //for each stat, loop through all group names and add it to the corresponding one
            for (String days30 : last30days) {
                if (hasTimeAndAction && statDay == days30) {
                    integer myint;
                    if (groupNamesMap.get(days30).get(st.Group__c) == null) {
                        myint = 0;
                    } else {
                    	myint = groupNamesMap.get(days30).get(st.Group__c);
                    }
                    
                    groupNamesMap.get(days30).put(st.Group__c, myint+1);
                    
                } else {
                    system.debug('%%% NULL FOUND & FILTERED ---------------------- ' + string.ValueOf(st.Id));
                }
            }
        }        
        
        //create new data objects based on map and submap values
        for (String s : last30days) {
            data.add(new Data(s, groupNamesMap.get(s).get('CM_Group_NameExample1'), groupNamesMap.get(s).get('CM_Group_NameExample2'), 0));
            
        }
        
        return data;
    }
    
    // Wrapper class
    public class Data {
        public String name { get; set; }
        public Integer data1 { get; set; }
        public Integer data2 { get; set; }
        public Integer data3 { get; set; }
        public Data(String name, Integer data1, Integer data2, Integer data3) {
            this.name = name;
            this.data1 = data1;
            this.data2 = data2;
            this.data3 = data3;
        }
    }
}
And here is the VF page:
<apex:page controller="BarChartController">
    <apex:chart height="400" width="700" data="{!data}">
        <apex:legend position="right"/>
        <apex:axis type="Numeric" position="left" fields="data1,data2" 
                   title="MyDataTitleHere" grid="true" minimum="0"/>
        <apex:axis type="Category" position="bottom" fields="name" 
                   title="Date (last 30 days)" minimum="0">
            <apex:chartLabel rotate="330"/>
        </apex:axis>
        <apex:lineSeries axis="left" fill="false" xField="name" yField="data1"
                         markerType="circle" markerSize="4" markerFill="#FF0000" />
        <apex:lineSeries axis="left" fill="false" xField="name" yField="data2"
                         markerType="cross" markerSize="5" markerFill="#FF0000" />
    </apex:chart>
</apex:page>

What I need the code to do (I think) is generate the constructors in the wrapper using the values present in groupNamesSet. From there, I need the code in the section "//create new data objects based..." to basically do this (to dynamically create Data objects and fill in the constructors by getting values from the map using the names from the groupNamesSet, which the values are already keyed by in the map):
data.add(new Data(s, groupNamesMap.get(s).get(groupNamesSet[0]), groupNamesMap.get(s).get(groupNamesSet[1], groupNamesMap.get(s).get(groupNamesSet[3], ETC)));
How can I achieve this?

Or, are there other methods that I should use to deal with the problem of a dynamic list of values to plot like in this example (where groupNamesSet could have any number of different values depending on the underlying data)?

Thanks!
 
Hello,

I've created a custom object (Hearing Results) that appears as a related list on most Contact page layouts.

Here's the related list on the contact:

User-added image

And here is one of those records with it's attachment:

User-added image

Is it possible to have a column in the first screenshot, on the related list, that lets the user view the attachment that is on the associated Hearing Results record? (just like how there's a "view" link for the attachment once you actually click through to the Hearing Result record)

Thanks!

Hi all,

I'm writing an apex class that is called by a Detail Page Button to do several things. It creates a new record in a custom object called "Hearing Result". I'd like to copy the current case's Case Email attachments to this new record in the custom object.

How can I do this?

Here is my apex class so far:
 

global class logHearingResult{
    
  WebService static id createHearingResult(Id currentCase) {
   
    //new set to hold current case Ids
    Set<Id> caseIds = new Set<Id>();
    
    //add current case Id to above set (currentCase is passed from javascript button)
    caseIds.add(currentCase);
    
      
    //new list to hold cases with the current case's Id
    List<Case> results = [
        select Id, Priority, ContactId
        from Case
        where Id in :caseIds
    ];	
    
    List<Hearing_Result__c> resultsToInsert = new List<Hearing_Result__c>();  
     
    id newHearingResultLocation;
    
    //work based on current case
    for (Case c : results){
        Hearing_Result__c ins = new Hearing_Result__c (ContactID__c = c.ContactId);
		resultsToInsert.add(ins);
        
        insert ins;
        newHearingResultLocation = ins.id;
    }
    
    update results;
    return newHearingResultLocation;
      
  }
    
}
Thanks!
Hi all,

I'm getting the following error with a Detail Page Button that runs an apex class.

User-added image

Here is the apex class:
 
global class logHearingResult{
    
  WebService static Id changePriority(Id currentCase) {
   
    //new set to hold current case Ids
    Set<Id> caseIds = new Set<Id>();
    
    //add current case Id to above set (currentCase is passed from javascript button)
    caseIds.add(currentCase);
    
      
    //new list to hold cases with the current case's Id
    List<Case> results = [
        select Id, Priority
        from Case
        where Id in :caseIds
    ];    
    
    //set caseIdToReturn to first Id in results list (this is just for test where popup from button displays current case Id)
    id caseIdToReturn = results.get(0).Id;
    
    List<Hearing_Result__c> resultsToInsert = new List<Hearing_Result__c>();  
    
    //work based on current case
    for (Case c : results){
        c.Priority = 'High';
        Hearing_Result__c ins = new Hearing_Result__c (ContactID__c = c.ContactId);
        resultsToInsert.add(ins);
    }
    
    insert resultsToInsert;
    update results;
    return caseIdToReturn;
      
  }
    
}
On line 27, I am assigning the ContactID__c value to the same contact ID that is associated with the current case. This is why I'm confused by the error.

Is it because I'm using a List to store the values to be inserted (and this can't hold the assigned ID)?

Thanks!
Hi all,

I'm creating a Detail Page Button that runs through various methods in an apex class. To get it up and running, I'm simply trying to return the current caseID in a pop-up. Here's the button code I'm using:
{!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/14.0/apex.js")} 

var thisCase = {!Case.Id}; 

var result = sforce.apex.execute( 
"logHearingResult",       // class 
"changePriority",         // method 
{currentCase: thisCase}); // method arguments 


alert(result + " is the current caseID."); //response

And here is the apex class:
 
global class logHearingResult{

  WebService static Integer doMath(Integer number1, Integer number2) {
    
    integer mathResult;
	mathResult = number1 + number2;
    
    return mathResult;
      
  }
    
    
  WebService static Id changePriority(Id currentCase) {
   
    Set<Id> caseIds = new Set<Id>();
      
    caseIds.add(currentCase);
      
    List<Case> results = [
        select Id
        from Case
        where Id in :caseIds
    ];	
    
    id caseIdToReturn;
    caseIdToReturn = results.get(0).Id;
      
    return caseIdToReturn;
      
  }
    
}

When I click the button, I just get the error: "Unexpected identifier"

I posted both because I'm not sure if this is a problem with my javascript or apex code. There's also that unused method doMath in the class.

Eventually I want the apex class to (1) update a field on the current case (change Status to 'Closed'), (2) open the case email attachments associated with the current case in a new window, (3) create a record in a custom object with some info already filled out (based on some fields on the case), and (4) copy the case email attachments associated with the current case to the newly created record.

I'm assuming most of the above is outside the scope of this question, but I'm trying to get started on that path.

And help is appreciated. Thanks!
Hi all,

I'm using a trigger to count the number of opps on an account, then label the current opp (as it's being inserted) either "Old Business" or "New Business". I know that the count oppCount_var does hold the correct number of opps for the current Account. The problem is when I go to update the field on the opp, nothing happens.
 
trigger newVsOldBusiness on Opportunity (before insert) {

    //create set to hold the current opp's associated Account ID
    Set<Id> CurrentOppAccountID = new Set<Id>();
    
    for (Opportunity o: Trigger.new) {
    	CurrentOppAccountID.add(o.AccountId);
    }
    
    integer oppCount;
    integer oppCount_var;
    
    //count all opps on Account object associated with current opp's Account ID
    AggregateResult[] AccountsByOppCount = [SELECT count(Id)oppCount
                                       				FROM Opportunity
                                       				WHERE AccountId in :CurrentOppAccountID group by AccountId
                                            		LIMIT 1];
    
    //loop over the aggregate result set
	for (AggregateResult ar : AccountsByOppCount) { 
		oppCount_var = integer.valueOf(ar.get('oppCount'));
	}

    System.debug('oppCount_var at line 18: ' + oppCount_var);
    
    //search for Type_of_Business__c on Opp    
    List<Opportunity> OppToUpdate = [SELECT Type_of_Business__c
                                                       FROM Opportunity
                                      				   WHERE AccountId in :CurrentOppAccountID
                                       				   LIMIT 1];
    
    if (oppCount_var>1) {
        for (Opportunity oppot: OppToUpdate) {
            oppot.Type_of_Business__c = 'Old';
            oppot.Accessory_Insert_Sent__c = true;
            System.debug('IN LOOP 1 BEFORE UPDATE');
            update OppToUpdate;
            System.debug('IN LOOP 1 AFTER UPDATE');
        } 
    } else {
        for (Opportunity oppot: OppToUpdate) {
            oppot.Type_of_Business__c = 'New';
            update OppToUpdate;
            System.debug('IN LOOP 2');
        }
    }

        
}

Here's the relevant debug for it:
 
14:13:13.18 (194613807)|USER_DEBUG|[45]|DEBUG|IN LOOP 1 BEFORE UPDATE
14:13:13.18 (194621079)|STATEMENT_EXECUTE|[46]
14:13:13.18 (194688155)|DML_BEGIN|[46]|Op:Update|Type:Opportunity|Rows:1
14:13:13.18 (194721316)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:13:13.221 (221153364)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:13:13.221 (221201260)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:13:13.221 (221233789)|ENTERING_MANAGED_PKG|npe01
14:13:13.221 (221267697)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:13:13.221 (221281371)|VARIABLE_SCOPE_BEGIN|[30]|this|npe01.OpportunityPayments|true|false
14:13:13.221 (221348248)|VARIABLE_ASSIGNMENT|[30]|this|{}|0x51733c3c
14:13:13.221 (224853834)|SOQL_EXECUTE_BEGIN|[107]|Aggregations:1|select id, CloseDate, Amount, isClosed, isWon, payments_made__c, (SELECT id, Paid__c, Payment_Amount__c, Payment_Date__c, scheduled_date__c from Opportunity.OppPayment__r) from Opportunity WHERE id in :newOpps
14:13:13.221 (233545826)|SOQL_EXECUTE_END|[107]|Rows:1
14:13:13.234 (234287513)|CUMULATIVE_LIMIT_USAGE
14:13:13.234 (234287513)|CUMULATIVE_LIMIT_USAGE_END

14:13:13.18 (260858150)|DML_END|[46]
14:13:13.18 (260931890)|STATEMENT_EXECUTE|[47]
14:13:13.18 (260946548)|HEAP_ALLOCATE|[47]|Bytes:22
14:13:13.18 (261028354)|USER_DEBUG|[47]|DEBUG|IN LOOP 1 AFTER UPDATE

Anyone know why this loop isn't updating the current opp as it's being inserted?

Thanks!
Hello,

I've created a trigger on the Case object that checks to see if a certain checkbox field on the case is checked. If the box is checked, it will update a field on the Contact that is associated with that case. This part is working perfectly.

The next step is to only update the Contact if the current case is the first case associated with that Contact. If not, the trigger should do nothing. What's the best way to add that functionality to this existing trigger?
 
trigger unqualifyProbablySPAMFromTalkdesk2 on Case (before insert, before update) {

    //create set to hold the current case ID
    Set<Id> CurrentCaseContactID = new Set<Id>();
    
	//if current case is marked as SPAM, add to the above list
    for (Case c: Trigger.new) {
        if (c.We_Think_It_s_SPAM__c == true) {
            CurrentCaseContactID.add(c.ContactId);
        }    
    }
    
    //query Contact object for the entry with ContactId matching the current case
    List<Contact> ContactForUpdating = [SELECT Trigger_Test2__c
                                                       FROM Contact
                                      				   WHERE Id = :CurrentCaseContactID];
    
    //set the fields we want to update on the associated Contact
    for (Contact item: ContactForUpdating) {
        item.Trigger_Test2__c = 'worked';
    }
    
    //update the associated Contact
    update ContactForUpdating;
}

I'm trying to figure out how to count all cases associated with the current Contact, and either run this trigger if that sum <1 or do nothing.

Any help is appreciated as I'm very new to Apex (as you can probably see in the above code).

Thanks!
I'm trying to create a custom button that will appear on every case. It will allow the current user to click it and take ownership of the case.

This is the code I'm using (which I basically copied from the button I have for this same purpose on the Contact):
 
{!requireScript("/soap/ajax/33.0/connection.js")} 

var case = new sforce.SObject("Cases"); 
case.id = '{!Case.Id}'; 
case.ownerId= '{!$User.Id}'; 
var result = sforce.connection.update([case]); 

if (result[0].success=='false') {
     alert(result[0].errors.message);
} else {
     location.reload(true);
}

When I click the button, I get the error: "Unexpected token case"

Anyone know what I'm doing wrong here?

Thanks!
Hello,

I have what I think is a simple question. I am trying to do the following:
  1. Have the formula look at MK_Days_When_Postmarked__c
  2. If it is blank, run throught the 4 calculations regarding trial date messages
  3. If it is not blank, run TEXT(MK_Days_When_Postmarked__c) (ie. show the number in that field)
 
IF( ISNULL(MK_Days_When_Postmarked__c),

IF(  MK_Days_Into_Trial__c = 0 , "Not Yet Shipped" ,

IF(  MK_Days_Into_Trial__c < 46 , "Day " + TEXT(MK_Days_Into_Trial__c) , 

IF(  MK_Days_Into_Trial__c < 51 , "Manually Calculate (~" + TEXT(MK_Days_Into_Trial__c) +" Days)" , 

IF(  MK_Days_Into_Trial__c > 50 ,"Out of Trial (" + TEXT(MK_Days_Into_Trial__c) + " Days)",

TEXT(MK_Days_When_Postmarked__c)

)
)
)
)
)

There's a good chance I'm making a simple mistake here, just can't seem to find it.

Thanks!
Hi all,

I'm getting the following error with a Detail Page Button that runs an apex class.

User-added image

Here is the apex class:
 
global class logHearingResult{
    
  WebService static Id changePriority(Id currentCase) {
   
    //new set to hold current case Ids
    Set<Id> caseIds = new Set<Id>();
    
    //add current case Id to above set (currentCase is passed from javascript button)
    caseIds.add(currentCase);
    
      
    //new list to hold cases with the current case's Id
    List<Case> results = [
        select Id, Priority
        from Case
        where Id in :caseIds
    ];    
    
    //set caseIdToReturn to first Id in results list (this is just for test where popup from button displays current case Id)
    id caseIdToReturn = results.get(0).Id;
    
    List<Hearing_Result__c> resultsToInsert = new List<Hearing_Result__c>();  
    
    //work based on current case
    for (Case c : results){
        c.Priority = 'High';
        Hearing_Result__c ins = new Hearing_Result__c (ContactID__c = c.ContactId);
        resultsToInsert.add(ins);
    }
    
    insert resultsToInsert;
    update results;
    return caseIdToReturn;
      
  }
    
}
On line 27, I am assigning the ContactID__c value to the same contact ID that is associated with the current case. This is why I'm confused by the error.

Is it because I'm using a List to store the values to be inserted (and this can't hold the assigned ID)?

Thanks!
We have a batch process that updates the # of business days in the current month on our account records.  It is returning a value of 21 for January even though the number of business days in January is 22.  We don't have any holidays built in our system for January.  Any suggestions as to what we are doing wrong would be appreciated.  

 global void execute(Database.BatchableContext BC, List<Account> scope) {
    
        if(scope.size()>0){
            list<Account> accountList = new list<Account>();
            list<BusinessHours> busHoursList = new list<BusinessHours>();
            busHoursList  = [SELECT ID FROM BusinessHours WHERE isActive = TRUE ORDER BY LastModifiedDate DESC LIMIT 1];
            if(busHoursList.size()>0){
                try{                
                    Date startDateMonth = Date.Today().toStartofMonth();
                    Date endDateMonth   = startDateMonth.addMonths(1).addDays(-1);
                    DateTime startTime = DateTime.newInstance(startDateMonth.year(), startDateMonth.month(), startDateMonth.day());
                    DateTime endTime = DateTime.newInstance(endDateMonth.year(), endDateMonth.month(), endDateMonth.day());
                    Decimal noOfWorkingDays = BusinessHours.diff(busHoursList[0].Id, startTime, endTime)/(3600*1000*24);
                    for(Account accObj : scope){
                        accObj.TAFS_Total_Business_Days_This_Month__c = noOfWorkingDays;
                        accountList.add(accObj);
                    }
                    if(!accountList.isEmpty()){
                        update accountList;
                    }                    
                }catch(DmlException dmlExcep){
                    //Do Nothing
                }
                catch(Exception excep){
                    //Do Nothing
                }           
            }               
        }
    }
When i execute the below test code:

@isTest
public class TestAfterInsert {   
    static testmethod void AItest(){   
     Account  a1 = new Account (Name = 'After Insert1', Phone = '1234567890');              
        Test.startTest();
        insert a1;
        Test.stopTest();
        Contact c = [Select LastName, Phone from contact where ID = :a1.id];       
        system.assertequals(c.lastname,a1.name);
        system.assertequals(c.phone,a1.phone);      
       }
     }

for below trigger :

trigger AfterInsert on Account (after insert) {
    List<Contact> cons = new List<Contact>();
    For(account a: trigger.new){       
        contact c = new contact();
        c.AccountId = a.Id;
        c.LastName = a.Name;
        c.Phone = a.Phone;       
        cons.add(c); 
    }
    insert cons;       
    }

I am receiving "System.QueryException: List has no rows for assignment to SObject"  error. Can someone please help me out to resolve the error?
 
formula field is not getting executed in test class, due to this condition is fails in apex class. the test class is below
@isTest(seealldata=false)
public class CreateOpty_Phyothersvcs_WPatsBatchTest {
static testMethod void test()
{
patient__C pat=new patient__C();
pat.name=test;
cost__C=100;
insert pat;

job__c jb = new job__c();
jb.name__c=test;
patient__C.id=pat.id;
//some field
insert jb;
//formula field in job object is patient_cost__c=patinet__r.cost__C

system.debug(''+jb.patient_cost__c);  //it showing null
//when i write query like

List<job__c> job = new List<job__c>();
job=[select id patient_cost__c from patient_cost__c where id=:jb.id];
 system.debug(''+job[0].patient_cost__c);  //it showing 100 correct as required

// but i want here 100
system.debug(''+jb.patient_cost__c);  //its still showing null
i've some formula field and another field update based on that formula field and thus
If formula field is Null then other field update operation will also be failed .
another it will not be cover test code coverage in apex class
in apex class i've used condtion like ex.
public class MySampleApexClass {
//some code
 List<job__c> jb=new List<job__c>();
 job=[select id,patient_cost__c from job__C where //some condition];
 for(job__c job : jb )
 {
		if(job.patient_cost__c<=50000) //this will fails(not cover in test class) due to formula field
			{ 
			
			//some code with different operation
			}
 }
 }



 
Hello experts, I need your help on a trigger. I have a requirement to calcualte the annual contract value for opportunities, this should be at both product level and at opportunity level. To be exact, i need to sum the first 12 months Revenue from productlineitemschedule at each productlineitem and then a total one at opportunity level. Could you please help with a sample code which could manage bulk record updates please. 
Hi, 

  I wrote a trigger which called apex class need a suggestion how to write the logic to get code coverage for test class. 

Apex Class
public with sharing class ApprovalUtils {

  /* Subscription Discount Level 1 */
  public static Integer SubLevel1(Decimal Subscription, Decimal ACV, Decimal Discount) {
    
   Integer L1Count;  
    
   List<AggregateResult> Level1 = [select count(id) Level1Count
              from Discount_Schedule_Matrix__c
              where
              Type__c = 'Subscription' and 
              Subscription_Term__c = :Subscription and
              ACV_Lower__c <= :ACV  and ACV_Upper__c >= :ACV and
              Sales_Rep_Lower__c <= :Discount and Sales_Rep_Upper__c >= :Discount];
              
              
    for (AggregateResult arLevel1 : Level1)
     {
       L1Count = ((Integer)arLevel1.get('Level1Count'));
       
     }         
                                     
    return L1Count;
  }
  
   /* Subscription Discount Level 2 */
   public static Integer SubLevel2(Decimal Subscription, Decimal ACV, Decimal Discount) {
    
   Integer L2Count;  
   
   List<AggregateResult> Level2 = [select count(id) Level2Count
              from Discount_Schedule_Matrix__c
              where
              Type__c = 'Subscription' and 
              Subscription_Term__c = :Subscription and
              ACV_Lower__c <= :ACV  and ACV_Upper__c >= :ACV and
              Direct_Manager_Lower__c <= :Discount and Direct_Manager_Upper__c >= :Discount];
              
              
    for (AggregateResult arLevel2 : Level2)
     {
      L2Count = ((Integer)arLevel2.get('Level2Count'));  
     }        
                                      
    return L2Count;
  }
  
   /* Subscription Discount Level 3 */
   public static Integer SubLevel3(Decimal Subscription, Decimal ACV, Decimal Discount) {
    
   Integer L3Count;  
   
   List<AggregateResult> Level3 = [select count(id) Level3Count
              from Discount_Schedule_Matrix__c
              where
              Type__c = 'Subscription' and 
              Subscription_Term__c = :Subscription and
              ACV_Lower__c <= :ACV  and ACV_Upper__c >= :ACV and
              SVP_Lower__c <= :Discount and SVP_Upper__c >= :Discount];
              
              
    for (AggregateResult arLevel3 : Level3)
     {
      L3Count = ((Integer)arLevel3.get('Level3Count'));
     }        
                                      
    return L3Count;
  }
  
  /* Subscription Discount Level 4 */
  public static Integer SubLevel4(Decimal Subscription, Decimal ACV, Decimal Discount) {
    
   Integer L4Count;  

   List<AggregateResult> Level4 = [select count(id) Level4Count
              from Discount_Schedule_Matrix__c
              where
              Type__c = 'Subscription' and 
              Subscription_Term__c = :Subscription and
              ACV_Lower__c <= :ACV  and ACV_Upper__c >= :ACV and
              CEO_CFO__c <= :Discount and CEO_CFO_Upper__c >= :Discount];
              
              
    for (AggregateResult arLevel4 : Level4)
     {
      L4Count = ((Integer)arLevel4.get('Level4Count'));
     }        
                                      
    return L4Count;
  }
  
  /* Service Discount Level 1 */
  public static Integer SerLevel1(Decimal ACV,Decimal Discount) {
    
   Integer L1Count;  
   
   List<AggregateResult> Level1 = [select count(id) Level1Count
              from Discount_Schedule_Matrix__c
              where
              Type__c = 'Services' and 
              Subscription_Term__c = 1 and
              ACV_Lower__c <= :ACV  and ACV_Upper__c >= :ACV and
              Sales_Rep_Lower__c <= :Discount and Sales_Rep_Upper__c >= :Discount];
              
              
    for (AggregateResult arLevel1 : Level1)
     {
      L1Count = ((Integer)arLevel1.get('Level1Count'));
     }        
                                      
    return L1Count;
  }
  
  /* Service Discount Level 2 */
    public static Integer SerLevel2(Decimal ACV,Decimal Discount) {
    
   Integer L2Count;  
   
   List<AggregateResult> Level2 = [select count(id) Level2Count
              from Discount_Schedule_Matrix__c
              where
              Type__c = 'Services' and 
              Subscription_Term__c = 1 and
              ACV_Lower__c <= :ACV  and ACV_Upper__c >= :ACV and
              Direct_Manager_Lower__c <= :Discount and Direct_Manager_Upper__c >= :Discount];
              
              
    for (AggregateResult arLevel2 : Level2)
     {
      L2Count = ((Integer)arLevel2.get('Level2Count'));
     }        
                                      
    return L2Count;
  }


  /* Service Discount Level 3 */
    public static Integer SerLevel3(Decimal ACV,Decimal Discount) {
    
   Integer L3Count;  
   
   List<AggregateResult> Level3 = [select count(id) Level3Count
              from Discount_Schedule_Matrix__c
              where
              Type__c = 'Services' and 
              Subscription_Term__c = 1 and
              ACV_Lower__c <= :ACV  and ACV_Upper__c >= :ACV and
              SVP_Lower__c <= :Discount and SVP_Upper__c >= :Discount];
              
              
    for (AggregateResult arLevel3 : Level3)
     {
      L3Count = ((Integer)arLevel3.get('Level3Count'));
     }        
                                      
    return L3Count;
  }
  
  
    /* Service Discount Level 3 */
    public static Decimal GetSubscriptionTerm(list<Id> Quoteid ) {
     
     Decimal SubscriptionTerm;
     
    /* Get Subscription Term */ 
    List<AggregateResult> MaxSubscrioptionYear = [select max(Subscription_Years__c) QSubscriptionYear 
                                                  from QuoteLineItem where quoteid in :Quoteid]; 
  
    
    for (AggregateResult GetSubscriptionYear : MaxSubscrioptionYear)
    { 
     SubscriptionTerm = (Decimal)GetSubscriptionYear.get('QSubscriptionYear');
      }
 
       return SubscriptionTerm;
    }
    
    
    
    
    
}
Trigger
trigger GenQuoteApproval on QuoteLineItem (After Insert, After Update, After Delete) {

  Decimal LineMaxDiscount;
  Decimal LineMaxACV;
  Decimal SubLineMaxDiscount;
  Decimal SubLineMaxACV;
  Decimal SerLineMaxDiscount;
  Decimal SerLineMaxACV;
  Map<ID, Quote> ParentQuote = new Map<ID, Quote>();
  String SALREPID;
  String MRGID;
  String SALID;
  String CFOID;
  String Level;
  Integer GSublevel1Count;
  Integer GSublevel2Count;
  Integer GSublevel3Count;
  Integer GSublevel4Count;
  Integer GSerlevel1Count;
  Integer GSerlevel2Count;
  Integer GSerlevel3Count;
  Decimal SubscriptionTerm;
 
Try 
{
if ( Trigger.isAfter)
  {
 List<Id> listIds = new List<Id>();
 //Set<Id> listIds = new Set<Id>();

 List<Quote> QuotetList = new List<Quote>();

 /* Get Quote ID */
 for (QuoteLineItem childquoteline :  Trigger.new)
 {
        listIds.add(childquoteline.QuoteId);
    }

 ParentQuote = new Map<Id, Quote>([SELECT id,Level_1__c,Level_2__c,Level_3__c,Level_4__c FROM Quote WHERE ID IN :listIds]);


  /* Get service list of all quote id */
  list<id> serviceid = new list<id>();
  for(QuoteLineItem getserviceid : [select id  from  QuoteLineItem
                                     where quoteid in :listIds and
                                           product2.Productcode  like 'CBSVC%'] )
   {
      serviceid.add(getserviceid.id);

   }

  /* Get subscription list of all quote id */
  list<id> subscriptionid = new list<id>();
  for(QuoteLineItem getsubscriptionid : [select id  from  QuoteLineItem
                                     where quoteid in :listIds and
                                           Subscription_Terms__c <> 0] )
   {
      subscriptionid.add(getsubscriptionid.id);

   }

 /* Subscription Discount and ACV */
    List<AggregateResult> MaxSubscription = [select max(Discount_Percent__c) SubQuoteLineMaxDiscount,sum(f_ACV__c) SubQuoteLineMaxACV
                                                   from  QuoteLineItem
                                                   where quoteid in :listIds and Subscription_Terms__c <> 0 and
                                                         ID not in :serviceid
                                                 ];

  for (AggregateResult SubQuoteMaxDiscount : MaxSubscription)
  {
  SubLineMaxDiscount = (Decimal)SubQuoteMaxDiscount.get('SubQuoteLineMaxDiscount');
  SubLineMaxACV = (Decimal)SubQuoteMaxDiscount.get('SubQuoteLineMaxACV');
  }

   system.debug('Subscription Line Discount  :' + SubLineMaxDiscount);
   system.debug('Subscription Line ACV  :' + SubLineMaxACV);

   /* Service Discount and ACV */
  List<AggregateResult> MaxService = [select max(Discount_Percent__c) SerQuoteLineMaxDiscount,SUM(f_ACV__c) SerQuoteLineMaxACV
                                      from  QuoteLineItem
                                      where quoteid in :listIds and product2.Productcode  like 'CBSVC%' and
                                            id not in :subscriptionid];

  for (AggregateResult SerQuoteMaxDiscount : MaxService)
  {
  SerLineMaxDiscount = (Decimal)SerQuoteMaxDiscount.get('SerQuoteLineMaxDiscount');
  SerLineMaxACV = (Decimal)SerQuoteMaxDiscount.get('SerQuoteLineMaxACV');
  }

   system.debug('Service Line Discount  :' + SerLineMaxDiscount);
   system.debug('Service Line ACV  :' + SerLineMaxACV);

  Opportunity Opp = [select ownerid
                    from opportunity
                    where
                    id in (select OpportunityId from quote where id in :listIds) ];

  system.debug(listIds);
  
  SubscriptionTerm = ApprovalUtils.GetSubscriptionTerm(listIds);

  system.debug('Get New Subscription Term' + SubscriptionTerm);
  
  /* Get Manager ID */
  User Usr = [select managerid from user where id = :opp.ownerid];

 /* Subscription Query to get level 1..4 values */
   if ( SubscriptionTerm != null &&
        SubLineMaxACV != null &&
        SubLineMaxDiscount != null)
   {
       GSublevel1Count = ApprovalUtils.SubLevel1(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level1 :' + GSublevel1Count);

       GSublevel2Count = ApprovalUtils.SubLevel2(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level2 :' + GSublevel2Count);

       GSublevel3Count = ApprovalUtils.SubLevel3(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level3 :' + GSublevel3Count);

       GSublevel4Count = ApprovalUtils.SubLevel4(SubscriptionTerm , SubLineMaxACV , SubLineMaxDiscount);

       system.debug('Subscription Level4 :' + GSublevel4Count);

        
   }

    /* Service Query to get level 1..4 values */
   if (SerLineMaxACV != null && SerLineMaxDiscount != null)
    {
       GSerlevel1Count = ApprovalUtils.SerLevel1(SerLineMaxACV,SerLineMaxDiscount);

       system.debug('Service Level1 :' + GSerlevel1Count);

        GSerlevel2Count = ApprovalUtils.SerLevel2(SerLineMaxACV,SerLineMaxDiscount);

       system.debug('Service Level2 :' + GSerlevel2Count);

        GSerlevel3Count = ApprovalUtils.SerLevel3(SerLineMaxACV,SerLineMaxDiscount);

       system.debug('Service Level3 :' + GSerlevel3Count);
    }    
   
   
   If( GSublevel1Count >= 1  || GSerlevel1Count >= 1  )
     {
      SALREPID = Opp.OwnerId;
      }   
     
     
    If (GSublevel2Count >= 1 || GSerlevel2Count >= 1  )
    {
      SALREPID = NULL;
      MRGID = Usr.managerid;
    }
       
    
    /* Future here you may have to change for amount > 1000000 if its going only to SVP */
   If ( GSublevel3Count >= 1 || GSerlevel3Count >= 1)
      {
      SALREPID = NULL;
      MRGID = Usr.managerid;
      SALID = '00580000007jaoA';
      }
      
    If ( GSublevel4Count >= 1 )
    {
    SALREPID = NULL;
    MRGID = Usr.managerid;
    SALID = '00580000007jaoA';
    CFOID = '00580000006HV0w';
    Level = '4sub';
    }  
  
    //system.debug('Which Level :' + Level);
    system.debug('Sales Rep :' + SALREPID);
    system.debug('Manager :' + MRGID);
    system.debug('Sales Ops :' + SALID);
    system.debug('CEO CFO :'  + CFOID);

for (QuoteLineItem gqtl : Trigger.new)
 {
   Quote MyParentQuote = ParentQuote.get(gqtl.QuoteId);

    MyParentQuote.Test_Sudhir__c = String.valueOf(LineMaxDiscount);
    MyParentQuote.Test_Sudhir_ACV__c = String.valueOf(LineMaxACV);
    MyParentQuote.Level_1__c = SALREPID;
    MyParentQuote.Level_2__c=MRGID;
    MyParentQuote.Level_3__c=SALID;
    MyParentQuote.Level_4__c=CFOID;
    MyParentQuote.Test_Sudhir_Level__c=Level;
  }

  update ParentQuote.values();

 }
}

catch(Exception e) {
    System.debug('The following exception has occurred: ' + e.getMessage());    
}
  
}


 
  • June 30, 2016
  • Like
  • 0
I am trying to create an Apex Class/Process Flow that posts on Slack when an Opportunity is closed won.

The amount is not populating correctly and is coming as '10000' opposed to $10,000'.
 
public class Oppty {
        @InvocableVariable(label='Opportunity Name')
        public String opptyName;
        @InvocableVariable(label='Stage')
        public String stage;
        @InvocableVariable(label='Opportunity First Name')
        public String opptyFirstName;
        @InvocableVariable(label='Opportunity Last Name')
        public String opptyLastName;
        @InvocableVariable(label='Opportunity Amount')
        public Decimal opptyAmount;  
    }

 
Hi, I need to retrieve file from third party and store the file contents in the SF objects.Can anyone please help me?
I have a requirement. Contact related to Task, I need to pull his functional role ( custom field) on Task page layout. So whenever I create or edit a Task and relate with any contact so his/her functional role ( Custom field) Value should populate automatic on Task Page field( Functional role).

Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not working. Please check my code and let me know what I am doing wrong.

Please find below code:
 
trigger updatefunctionalrole on Task (before insert, before update) {

Map<ID,String> confunrole = new Map<ID,String>();
List<Task> conTasks = new List<Task>();


for (Task e : trigger.new) {

    if (e.whoID!= null && (String.valueOf(e.whoID)).startsWith('003'))  {

        if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
            confunrole.put(e.whoID,'');
            conTasks.add(e);
        }
    }
}

for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
    confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Task with the relevant value
for (Task e : trigger.new) {
    e.functional_role__c = confunrole.get(e.whoID);
}
}

 
When I scheduled batch apex, I'm getting this error, Please help me
global class batchLogBookManagementV2 implements Database.Batchable<sObject>, Database.Stateful {

global List<Log_Book__c> logToBeContinued = new List<Log_Book__c> ();
global List<Log_Book__c> logToBeInserted = new List<Log_Book__c> ();    
global List<Subject_Registered__c> sbsr = new List<Subject_Registered__c> ();
    
    global List<Weeks__c> weekList = Weeks__c.getAll().values();
    global Map<Integer, Weeks__c> weekMap = new Map<Integer, Weeks__c>();
    global Map<String, Integer> weekMapGetIntWithWeek = new Map<String, Integer>();    
    global Map<String, Subjects_and_Levels__c> subjectLevelMap =  Subjects_and_Levels__c.getAll();
    global List<Subjects_and_Levels__c> subjectLevelList = subjectLevelMap.values();
    global Map<String, Subjects_and_Levels__c> levelMap = new Map<String, Subjects_and_Levels__c>();
    

        
global final String query = 'SELECT id,Last_Schedule__c, Level__c, Student__c, Subject__c, Week__c, (SELECT Student__c, Subjects_Registered__c, Subject__c, Class_Scheduled_Date__c, Level__c, Week__c FROM Log_Books__r ORDER By Class_Scheduled_Date__c DESC NULLS FIRST LIMIT 1 ) FROM Subject_Registered__c WHERE Deactivated__c = false AND Last_Schedule__c != null';
 
 
global Iterable<sObject> start(Database.BatchableContext BC){
     sbsr = Database.query(query);
     for(Subject_Registered__c s: sbsr)
     {
         logToBeContinued.add(s.log_Books__r[0]);         
     }
    
    return logToBeContinued;
    }
 
global void execute(Database.BatchableContext BC,List<Log_Book__c> scope){
     for(Subjects_and_Levels__c level: subjectLevelList)
     {
     system.debug('level : '+level);
         if(level !=null)
         levelMap.put(level.subject__c+Integer.valueof(level.Order__c), level);
         else
             system.debug('error as level null');
     }
    for(Weeks__c week : weekList)
    {
    system.debug('week : '+week);
        if(week != null){
            weekMap.put((Integer)week.Order__c, week);
            weekMapGetIntWithWeek.put(week.Name, (Integer)week.Order__c);
        }
    }
     System.debug('++++++++++++++++++++++++   : ' + scope);
     for(Log_Book__c s: scope)
     {
         
         System.debug('logToBeInserted--------------------------------   : ' + logToBeInserted.size());
         System.debug('--------------------------------   : ' + s);
         Integer totalLevels = 0;
          if(s.Subject__c == 'English')
            totalLevels = 15;
          else if(s.Subject__c == 'Abacus')
            totalLevels = 11;
          else if(s.Subject__c == 'Math')
            totalLevels = 14;
          else if(s.Subject__c == 'G.K')
            totalLevels = 4;
         System.debug('xxxxxxxxxxxxxxxx  : ' + subjectLevelMap);
          
         System.debug('@@Subject@@@@@@@'+subjectLevelMap.get(s.Subject__c+s.level__c) );
          
            if(subjectLevelMap.containsKey(s.Subject__c+':'+s.Level__c) && (s.Class_Scheduled_Date__c != null))
            {
                
            Integer levelOrder = Integer.valueof(subjectLevelMap.get(s.Subject__c +':'+s.Level__c).Order__c);
             system.debug('level order: '+levelOrder);
            Integer weekOrder = Integer.ValueOf(weekMapGetIntWithWeek.get(s.Week__c));
             system.debug('week order: '+weekOrder);
            
         Log_Book__c l = new Log_Book__c ();
         l.Student__c = s.Student__c;
         l.Subject__c = s.Subject__c;
         l.Subjects_Registered__c = s.Subjects_Registered__c;
         l.Class_Scheduled_Date__c = s.Class_Scheduled_Date__c.addDays(7);
                System.debug('class schedule date is--->'+l.Class_Scheduled_Date__c);
           
         if(s.Week__c == '26-Z')
         {
             if(levelOrder != null && levelOrder < totalLevels)
             {
                 levelOrder = levelOrder +1;
                 System.Debug('lb.Subject__c+levelOrder : '+ l.Subject__c+levelOrder);
                 l.level__c = levelMap.get(l.Subject__c+levelOrder).Level__c;
                 l.Week__c = '1-A';
                 logToBeInserted.add(l);
             }
             
         }
         else
          if(s.Subject__c == 'Math' && s.Level__c == 'Level 5B' && s.Week__c == '17-Q')
            {
              if(levelOrder != null && levelOrder < totalLevels)
             {
                 levelOrder = levelOrder +1;
                 System.Debug('lb.Subject__c+levelOrder : '+ l.Subject__c+levelOrder);
                 l.level__c = levelMap.get(l.Subject__c+levelOrder).Level__c;
                 l.Week__c = '1-A';
                 logToBeInserted.add(l);
             }
       
            }
         else
         {
                weekOrder = weekOrder+1;
                l.Week__c = weekMap.get(weekOrder).Name;
                l.Level__c = s.Level__c;
                logToBeInserted.add(l);
                    
         }
    }  
     }//for
    if(logToBeInserted.size()>0)
    {
               
        Database.UpsertResult[] srList = Database.upsert(logToBeInserted, false);
        
        // Iterate through each returned result
        for (Database.UpsertResult  sr : srList) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                System.debug('Successfully inserted LogBook. LogBook ID: ' + sr.getId());
            }
            else {
                // Operation failed, so get all errors                
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Account fields that affected this error: ' + err.getFields());
                }
            }    
        
        }
        
    }
     //System.debug('###############################  :' + ((Subject_Registered__c)scope.get(0)).log_Book__r.Class_Scheduled_Date__c);
     System.debug('Scope of the record is'+scope.size());
    // scope variable now has the records received from QueryLocator.
  //  delete scope;    
   // Database.emptyRecycleBin(scope);
    }
 
global void finish(Database.BatchableContext BC){
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id =:BC.getJobId()];
 
    // Send an email to the Apex job's submitter
    // notifying of job completion.
  
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BAtch: ' + a.Status);
 //mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures.');
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures and Status'+a.status);
 
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
  }
}

 
okay trying to find out the best way to do this. My company is moving from 4 digit locations numbers to 5 digits location numbers what is the best way to make sure that when the 5 digit location change that I can still see the 4 digit location data under the new 5 digit location in salesforce  
Hello, 

I need to make my trigger fire only when the case description is not null. is this the right way to approach this? I've really new to APEX and it's really throwing me for a loop. 

trigger descUpdate on Case (before update) {    
    case[] cases = Trigger.new;
    if(case.description !=null)
    caseDescUpdate.descUpdate(cases);
}

Thanks!

-Mike
Hi

I am trying to create a trigger after a record of a custom object called portfolio is created (accounts object is the master). Trying to update a text field on a portfolio record called portfolio number based on combining a number value from accounts field (called client ID) + "="+ and sequence number (1 2 3 4 ....) based on the no. of portfolio records created per account.

However I still want to manually update the text field and put a sequence no as required. Then if I try to create the next record it should pick up the next sequence no. from the highest sequence number in total portfolio records per account.

Can you help me in achievieng this request? Hope I make sense.
Thanks

Hi,

I'm new to Salesforce and I'm struggling since a few hours on how to bulkify this trigger.

I have an object called kognoz1__Invoice2__c linked with an opportunity through a lookup field. This object has 3 email custom fields :"Relance_Email__c","Relance_CC_Email__c" and "Relance__CC2_Email__c".

The trigger must copy the emails from the Contact Role of the Opportunity linked with my custom object in those 3 previous email fields. But only when the roles of the contacts are :"Decisionnaire et Comptabilité" or "Comptabilité" and moreover when a checkbox named  "Relance_Automatique" ( which is a custom field on the contact object ) is checked. 

The fact is that an opportunity can have one, two or three contact role corresponding to the conditions that's why I'm using three email custom fields in the kognoz1__Invoice2__c object.

Here is the trigger i made, it is working fine when I'm updating the kognoz records one by one but I would like to use a Batch in order to update a lot of records and I'm getting a "too many SOQL queries Error". 

 

trigger UpdateContactEmailRelance on kognoz1__Invoice2__c (before insert, before update) {
        for(kognoz1__Invoice2__c k : trigger.new){
        List<OpportunityContactRole> Contactsearch = [Select ContactId from OpportunityContactRole where OpportunityId=:k.kognoz1__Opportunity__c and (Role='Décisionnaire et Comptabilité' or Role='Comptabilité')];
        if(Contactsearch.size()==1){
            k.Relance_CC_Email__c='';
            k.Relance_CC2_Email__c='';
            Contact email1=[Select Email, Relance_Automatique__c from Contact where Id=:Contactsearch[0].ContactId];
            if(email1.Relance_Automatique__c=true){
                k.Relance_Email__c=email1.Email;
            }
            else k.Relance_Email__c='';
        }
        if(Contactsearch.size()==2){
            k.Relance_CC2_Email__c='';
            List<Contact> emails=[Select Email, Relance_Automatique__c from Contact where (Id=:Contactsearch[0].ContactId or Id=:Contactsearch[1].ContactId) and Relance_Automatique__c=true];
            if(emails.size()==1){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c='';
            }
            else if(emails.size()==2){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c=emails[1].Email;
            }
            else{
                k.Relance_Email__c='';
                k.Relance_CC_Email__c='';
            }
        }
        if(Contactsearch.size()==3){
            List<Contact> emails=[Select Email, Relance_Automatique__c from Contact where (Id=:Contactsearch[0].ContactId or Id=:Contactsearch[1].ContactId or Id=:Contactsearch[2].ContactId) and Relance_Automatique__c=true];
            if(emails.size()==1){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c='';
                k.Relance_CC2_Email__c='';
            }
            else if(emails.size()==2){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c=emails[1].Email;
                k.Relance_CC2_Email__c='';
            }
            else if(emails.size()==3){
                k.Relance_Email__c=emails[0].Email;
                k.Relance_CC_Email__c=emails[1].Email;
                k.Relance_CC2_Email__c=emails[2].Email;
            }
            else{
                k.Relance_Email__c='';
                k.Relance_CC_Email__c='';
                k.Relance_CC2_Email__c='';
            }
        }
    }
}


I know that I must bulkify it but I can't figure out how to do it. 

Thank you in advance !

Hey everybody,

I am getting the following error when I try and update multiple records (Feature Request custom object) through an enhanced list view. I know it has to do with I am querying multiple records but I don't know the best method to get this fixed. Does it have to do with maps? See apex code below. Thanks!
 
trigger UpdateOFR on Feature_Request__c (after update, after insert) { 

    Feature_Request__c fr = [Select Feature_Request_Status__c, Target_Release__c, Owner.Name from Feature_Request__c where ID IN :trigger.new];
    
    List<Opportunity_Feature_Request__c> lstToUpdate = new List<Opportunity_Feature_Request__c>();
	for(Opportunity_Feature_Request__c obj :[select Feature_Request_Status__c, Feature_Request_Target_Release__c, Feature_Request_Owner__c from Opportunity_Feature_Request__c where Feature_Request__c in : trigger.new]){
		
         
        obj.Feature_Request_Target_Release__c = fr.Target_Release__c;
        obj.Feature_Request_Owner__c = fr.Owner.Name;
        obj.Feature_Request_Status__c = fr.Feature_Request_Status__c;
		lstToUpdate.add(obj);
	}

	if(!lstToUpdate.isEmpty())
		update lstToUpdate;
}

I wrote a small trigger to populate a lookup field on the Opportunity object, and I can't seem to get my test class to enter the loop which contains the assignment of this field. The query appears to have all the necessary info, I'm not sure what's wrong.
Here is the trigger: 
 

trigger FillPrimaryPartner on Opportunity (before insert, before update) {
    for (Opportunity opp : trigger.new){
        for (Partner p : [select id from Partner where IsPrimary=true and AccountFromId =: opp.AccountId]){
            opp.Primary_Partner__c = p.Id; 
        }
    }
}
and here is its test class:
@isTest
public class TESTFillPrimaryPartner {
	static testMethod void insertNewData(){
        
        Account partAcct = new Account();
        partAcct.Type = 'Signed Partner';
        partAcct.Industry = 'Retail';
        partAcct.BillingCountry = 'Italy';
        insert partAcct;
        
        Account oppAcct = new Account();
        oppAcct.Type = 'Customer';
        oppAcct.Industry = 'CPG';
        oppAcct.BillingCountry = 'Italy';
        insert oppAcct;
        
        Opportunity opp1 = new Opportunity();
        Opportunity.AccountId = oppAcct.Id;
        insert opp1;
        
        Partner part1 = new Partner();
        part1.IsPrimary = true;
        part1.AccountFromId = oppAcct.Id;
        part1.AccountToId = partAcct.Id;
        insert part1;
    }
}


 
Hello,

I can't get this code to work. I keep getting the response, "{"Code":50,"Message":"Must supply a valid HTTP Basic Authorization header"}".

I'm trying to get data from Campaign Monitor, as shown here.

Here is the code I'm using:
Http httpProtocol = new Http();
HttpRequest request = new HttpRequest();
request.setEndPoint('https://api.createsend.com/api/v3.1/clients.json');


Blob headerValue = Blob.valueOf('u:' + '34534j5hk34j5hk34j5hk3j45hk3j'); //not my actual API key :)
String authorizationHeader = EncodingUtil.base64Encode(headerValue);
request.setHeader('Authorization', 'Basic ' + authorizationHeader);

//I've also tried it like this:
request.setHeader('Authorization', authorizationHeader);

request.setMethod('GET');
HttpResponse response = httpProtocol.send(request);
System.debug(response.getBody());

Are my headers missing info? I can't firgure out what it's looking for.

Thanks!