• Paul S.
  • SMARTIE
  • 750 Points
  • Member since 2014

  • Chatter
    Feed
  • 23
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 195
    Replies
Hello,
I am trying to get the recordId in another component. Therefore I wrote a extra Apex method but I am not sure how to get the recordId there. 

Here I need to have the recordId of a Contact to get the right data
/**
   * Returns a case by its ID
   *
   * @param      id    The identifier
   *
   * @return     The case.
   */
  @AuraEnabled
  public static Case getCaseWithContact(Id id) {
    return [
      SELECT
        Id,
        Contact.Name,
        Contact.LastName,
        Contact.FirstName,
        Contact.MailingStreet,
        Contact.MailingCountry,
        Contact.Country_ISO_3166_2__c,
        Contact.MailingPostalCode,
        Contact.MailingCity,
        Contact.Phone,
        Contact.MobilePhone,
        Contact.Fax,
        Contact.Email,
        Contact.CustomerNumberNav__c,
        Contact.CustomerNumberSF__c,
        Contact.SalutationNavisionExport__c
        FROM Case WHERE Id = :id

    ];
  }

I tryed to create a method that gets the recordId and then give it to the getCaseWithContact like:
 
@AuraEnabled
  public static String getIdFromContactInCaseString(Id id) {

    List <case> ownerIdRec = [SELECT VehicleOwner__c FROM Case WHERE Id = :id];

    String ownerIdRecord = ownerIdRec[0];

    return ownerIdRecord;

  }

But there I get the Error Illegal assignment from Case to String.

Can someone help me or give me a tipp?
 
Hi everyone,

could you please check and help me out
List<case> scope=new List<Case>([select id from case]);
Schema.SObjectType sObjectType = scope.getSObjectType();
String s=(string)sObjectType;
its not working
  • November 17, 2018
  • Like
  • 0
Hello,
I have the follwoing code being executed in a for loop and I want to remove it from the loop and bulkify it how would I do this?
A list, or a map? I preferer to use a map if possible.
 
Account_Procedure_Rate__c rate = [SELECT Amount_To_Pay__c, Procedure_Cost__c FROM Account_Procedure_Rate__c 
														 	 WHERE  CPT_Code__c = :proc.CPT_Code__c AND Main_Center__c = :centerId];
							proc.Amount_To_Pay__c = rate.Amount_To_Pay__c;
							proc.Procedure_Cost__c = rate.Procedure_Cost__c;



Thanks,
K
I recently started working with a freelancer to build some Apex triggers, and I am finding it difficult to hold him to the solution we need. It would be beneficial to get 5 minutes of an experienced Apex developer to see if there's a better way to achieve our goals that would be easier for the freelancer to develop.

We need a way of showing related server update fields on the relevant contact records. However, since contacts can have multiple accounts, we need a way of picking which server update to show (the newest created) on a contact record. Your input is appreciated.
Map of custom objects and relationships between them.
I have create a trigger that creates a custom object record (Training__c ) whenever the formula field Training Id (on Tasks) equals 1, and the task is completed. The code seems to be working fine in my sandbox however when I go to implement the test class I run into two issues: 

Issue number 1: When I run my test class I don't get any code coverage on the trigger after running it.
Issue number 2: When I try to deploy the trigger and class I get the following error:
       
System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: [] 
Stack Trace: Class.insertTraining.insertTraining: line 26, column 1.

I'm not quite sure what the Invalid_Cross_Refeference_Key  id is but I'm guessing it has to do with the task that I am creating. The code for both the class and trigger are below. Any assistance is greatly a ppreciated. 
 
Insert Training Trigger: 


trigger insertTraining on Task (after update) {
               
    for (Task task : Trigger.new) {
       
        if(task.Training_Id__c == 1 && task.Status == 'Completed' ){
            
            Training__c train = new Training__c();
 
 
 train.Name = task.Subject;
 train.Type__c = task.Activity_Type__c;
 train.Missed__c= task.Missed__c;
 train.Onsite__c= task.Onsite__c;
 train.Comments__c = task.Description;
 train.Related_To__c = Trigger.new[0].WhatId;
 train.Due_Date__c = task.ActivityDate;
 train.Start_Time__c = task.Start_Time__c;
 train.End_Time__c = task.End_Time__c;
 train.Concerns__c = task.Concerns__c;
 train.Next_Steps__c = task.Next_Steps__c;

 insert train;
             
        }
    }
}



insertTraining Test Class: 

@istest

public class insertTraining {
    static testMethod void insertTraining (){
    
    string parentId = '001p000000ObV3q';
      
    //Insert a new activity where Training ID is 1
    
    Task task = new Task();
    
    task.Subject= 'Task is 1';
        
    task.No_Connect__c =  True;
    task.Connect__c = False;
    task.Notes_and_Comments__c = 'This should be the record that is taken to create a training' ;
    task.ActivityDate = date.newInstance(2017, 10, 15);
    task.Start_Time__c = dateTime.newInstance(2017, 10, 15, 12, 30, 0); 
    task.End_Time__c = dateTime.newInstance(2017, 10, 15, 12, 45, 0) ;
    task.Activity_Type__c = 'Basic Training';
    task.WhatId = parentId;
    task.Status = 'Completed';
    
   
    
    insert task;
  
 
      
      
       // insert new Training record
    
    Training__c train = new Training__c();
    
    train.Name = task.Subject;
    train.Type__c  = task.Activity_Type__c;
    train.missed__c = task.missed__c;  
    train.onsite__c = task.onsite__c;
    train.Comments__c = task.Notes_and_Comments__c;
    train.Related_To__c = task.WhatId;
    train.Due_Date__c = task.ActivityDate;
    train.Start_Time__c = task.Start_Time__c;
    train.End_Time__c = task.End_Time__c;
    
    
    insert train;
        
     //find the number of all of the trainings that that have been created
     
    List<Training__c> train1 =[Select Id,Name, onsite__c, missed__c, Related_To__c, Start_Time__c, End_Time__c, Due_Date__c, Comments__c, Type__c FROM Training__c WHERE Id = :task.Whatid];
     
                    
     System.assertEquals(0,train1.size());
     
     
     
     
     
     
         
         
         
         }
     
     
  }
I'm still relatively knew to triggers and classes so any assistance or clarification is greatly appreciated. 
Hi,

PS: I am preparing a design so no code is written so far. 

In my custom object, I store the start and end dates of a particular campaign, let's say start date is 01/01/2017, the end date is 03/31/2018. For these 15 months, I need to create an opportunity (one for each month) and need to mark the close date as the end date of every month. This process of Opportunity creation is going to happen through a trigger.

I would like to check if anyone has done something similar to this and can share a code snippet or provide the best practices around this.

Thanks.
Below i am trying to replace User.Name with the name of my picklist field(Change_Owner__c) and then Cody Dren with whatever the user selected from the picklist(Cody D, Kyle W, Jen J etc).  Can someone please help me with this. 

Thanks.

Trigger UpdateOwnerID on Case (before insert, before update) {
       
    User objUser = [select Id from User where User.Name = 'Cody Drennon' limit 1];  
    for (Case objCase : Trigger.new)
    {
        if (objCase.OwnerId <> objUser.Id)               
        {
            objCase.OwnerId = objUser.Id;
        }
    }

}
Hi All,

I am completely lost with this code coverage message I keep on getting during my change set deployments (it's driving me crazy). Four out of the 5 error messages refer to a flow which I was able to locate via workbench but I don't know how to actually fix it. I'm not sure if turning off this specific flow during the deployments is best practice or if I should actually address this code issue -- how do I go about doing that? Any help suggestions or reference material is much appreciated. Below is a screenshot of the error message, thank you all in advance!

User-added image
  • December 11, 2017
  • Like
  • 0
Taking the challenge for the Getting Started With APEX triggers and found that the trigger code below did not work and had the stranger problem of Changing the Match_Billing_Address__c field to True whenever i tried to save an account.  After a few exasperating hours, i changed I (a.Match_Billing_Address__c=true) to  (a.Match_Billing_Address__c<>false) and it all started working and I passed the challenge.   I would be grateful for any explanation of this behavior.
 
trigger AccountAddressTrigger on Account (before insert, before update) {
    For (Account a : Trigger.new) { 
        If (a.Match_Billing_Address__c=true) {
        system.debug(a.Match_Billing_Address__c);
        a.ShippingPostalCode=a.BillingPostalCode;
    }    
    }
}

 
I have learnt the following about "Attributes" and "Variables". Could you please confirm if what I have learnt is correct or incorrect? (I am a bit confused with these two concepts now).
  • Attributes:
    • Are the "adjectives" or "parts" of a future object that is going to be constructed with a Constructor. I am guessing that we use the term "attribute" when we are, somehow, "designing" the object that will be constructed in the future.
    • Attributes are also called "properties"(?)
    • Example: we may be designing the future construction of a car (we design the car with a class "Car" where we specify all of its attributes which will be used by a Constructor which, in turn, will construct objects). When we design/define/specify these "parts" or "adjectives" , then I THINK that thats when we use the term "attributes". Right? (that's when we are still defining how objects are going to be)
    • An attribute, I think, is very similar to a Variable; the difference is that the attributes are to be used by a Constructor. Variables are not used in Constructors. Is that Right?
  • Variables:
    • Variables, I GUESS, are similar to attributes but they only start being called "Variables" when they have been declared as such which means they are capable of storing values. (attributes do not have this capability)
    • Once a Variable has been declared as a Variable, it becomes a "ready space in memory", ready to store values.

I am not sure if the above is 100% correct.
I suppose that what 's confusing me is the fact that the way Attributes are defined is similar to the way Variables are declared:

Here I define an attribute (should I use the term "define"? or...  some other term?):
mode type of NameOfClass nameOfAttribute;
Here below I declare a variable:
type or NameOfClass nameOfVariable;
I observe that, when defining an attribute, there is a "mode" (such as "private" or "public") but when declaring a variable, we do not include a "mode".

Could you possibly help me to clarify the conceptual difference between attribute and variable ?

Thank you.

 
  • November 20, 2017
  • Like
  • 0
Hi,

I am having a bit of trouble and cannot find an answer that fits what I need.

I have 2 custom objects totally unrelated. Assessment__c, and AsstCodes__c.

AsstCodes__c has 2 fields Name and Description. Both are text fields.

What I want to achieve is this:
When I save a new Assessment__c record I want a trigger to update the Assessment__c.Description with the AsstCodes__c.Description.
The common factor is that Assessment__c.Code__c (picklist) will be the same value as a record in AsstCodes__c.Name (text value)

So far I have minimal code for this.

I know I need to do the following:
AsstCodeDescription = [SELECT description__c FROM AsstCodes__c WHERE Assessment__c.Name = AsstCode.Name LIMIT 1];
trigger AsstDesc on Assessment__c (after insert, after update)
{
    map<string, Assessment__c> TheMap = new map<string, Assessment__c>();
        
    for (Assessment__c Desc:trigger.new)
    {
        if (Desc.Name !='')
        Desc.Description__c = AsstCodeDescription;
        update desc;
    }
    
}

I am just not sure how to put it all together.​ Hope this all makes sense.

Thanks for your help
Joe
 
I have the scenario that when ever stage is updated with closed won we are creating another open opportunity.
This update is manula update and working fine.
For same scenario we have workflow to update the record with closed won in this case after update trigger is not working fien.
could anyone suggest me the cause.its kind of priority to me now.
Hello,
Below is my batch class to find the minimum pageview/session rate if affiliated record  matches certain criteria.

Concept is simple, get all Monthly Activities in a LIST and compare their Pageview_Rate against Minimum_Pageview_Rate.
If it is higher, then replace the Minimum with Pageview_Rate.
Minimum_Pageview_Rate is a common value for all records for that ONE MONTH and YEAR.

The batch is executing , but isn't updating anything.
Can someone point out what I amy be doing wrong here.

I apologize in advance for any basic error.
I am not very adept in writing batch jobs.

Any help is appreciated.
Thanks!
global class BatchToFindFormerAuthorRate implements Database.Batchable<sObject>, Schedulable{
    
    global final string query;
	private Date currentDate = date.today();
    
    global BatchToFindFormerAuthorRate(){
       query = 'SELECT Id,Paid_On__c,FA_Pageview_Rate__c,FA_Session_Rate__c, Minimum_Pageview_Rate__c,Minimum_Session_Rate__c, Expert_Contract__r.Status__c, Month__c, Year__c ,Pageview_Rate__c, Session_Rate__c FROM Monthly_Activity__c';  
    	
    }
               
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Monthly_Activity__c> scope){			
        List<Monthly_Activity__c> monActList = new List<Monthly_Activity__c>();
       
        for(Monthly_Activity__c c : scope){
            if(c.Expert_Contract__r.Status__c == 'Live' && c.Month__c == currentDate.month() && c.Year__c == currentDate.year()){
                if(c.Paid_On__c == 'Pageviews' && c.Minimum_Pageview_Rate__c > c.Pageview_Rate__c ){
                    c.Minimum_Pageview_Rate__c = c.Pageview_Rate__c;
                    c.FA_Pageview_Rate__c = c.Minimum_Pageview_Rate__c/2;
                    monActList.add(c);       
            	}else if(c.Paid_On__c == 'Sessions' && c.Minimum_Session_Rate__c > c.Session_Rate__c){
                    c.Minimum_Session_Rate__c = c.Session_Rate__c;
                    c.FA_Session_Rate__c = c.Session_Rate__c/2;
                    monActList.add(c);
    	}
       }         
     }
     update monActList;        
 }      
    
    global void execute(SchedulableContext SC){
        Database.executeBatch(new BatchToFindFormerAuthorRate());                  
    }
    
    global void finish(Database.BatchableContext BC){
        List<String> EMAIL_RESULTS = new List<String>{System.Label.Email_List};
             
        AsyncApexJob apexBatchResult = [
            SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id =: BC.getJobId()
        ];
    
        // Generate email body
      
    

    }
 }

 
Hi friends,

I have a custome object in which I am saving records and their is a field with name Date_and_Time__c which is containing time and date for next schedule. I need a query which will give all records during current time and next 5 mints.  For example if current time is 4:30 PM and I have given time 4:32 PM in Date_and_Time__c field then it should return this record and if their is any other records during this interval then it sould give all records.
My code is as below:
*****************
global static string GetReminder(){  
        
        DateTime dt = datetime.now();
        DateTime dtIST = dt.addMinutes(330); //330 is GMT +5:30 as IST conversion
        //String CurrentdateTime = dt.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
        DateTime dt1 = dtIST.addMinutes(5); // 5 minutes after current time.
        
        List<SetReminder__c> reminderList = [Select Id, Name, Date_and_Time__c, Next_Best_Action__c, Recom_External_Id__c, Recommendation__c from SetReminder__c where (Date_and_Time__c >=: dtIST and Date_and_Time__c <=:dt1)];
      
        system.debug('DT:' + dtIST);
        system.debug('DT1:' +dt1);
        system.debug('ReminderList:' +reminderList);
         return null;
        }
   
Thanks in  advance
Regards:
Rajan   
  • September 19, 2017
  • Like
  • 0
got code coverage only 5% percentage how can i acheive this 75% more , please help me for 75% code coverage
trigger RepCompensation on Compensation__c(before insert, before update) {
for(Compensation__ccc: Trigger.New){
    List<Compensation__c> cclist =[select id,Contract__c,Payment_Amount__c,Payment_Frequency1__c,Frequency_Months__c,Payment_Due_Date__c,Payment_Date_2__c,Payment_Date_3__c,Payment_Date_4__c,Payment_Amount1__c FROM  Compensation__cWHERE id  in : Trigger.New];
    datetime cd = System.today();

  if((cc.Payment_Frequency1__c == 'Annually' || cc.Payment_Frequency1__c == 'One Time') & cc.Payment_Frequency1__c <> Null){
        If(cc.Frequency_Months__c <> Null && cc.Payment_Due_Date__c == Null){
      if(cc.Frequency_Months__c == 'January'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),01,01);
      }
        if(cc.Frequency_Months__c == 'February'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),02,01);
      }
        if(cc.Frequency_Months__c == 'March'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),03,01);
      }
        if(cc.Frequency_Months__c == 'April'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),04,01);
      }
        if(cc.Frequency_Months__c == 'May'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),05,01);
      }
        if(cc.Frequency_Months__c == 'June'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),06,01);
      }
        if(cc.Frequency_Months__c == 'July'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),07,01);
      }
        if(cc.Frequency_Months__c == 'August'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),08,01);
      }
        if(cc.Frequency_Months__c == 'September'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),09,01);
      }
        if(cc.Frequency_Months__c == 'October'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),10,01);
      }
        if(cc.Frequency_Months__c == 'November'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),11,01);
      }
        if(cc.Frequency_Months__c == 'December'){
      cc.Payment_Due_Date__c = date.newinstance(cd.year(),12,01);
      }
    }
    }

test class

@isTest
public class TestRepCompensation{
    
    public static testmethod void test1(){
        datetime cd = System.today();       
        Account a = new Account(Name = 'Test Account', Account_Type__c = 'Agency', Hierarchy_1__c = 'Growth', Hierarchy_2__c = 'Growth Miscellaneous',
                    Hierarchy_3__c = 'Growth Miscellaneous', Picklist_Category__c = 'Medical');
        insert a;
        Contract c = new Contract(Status = 'Proposed/pending',Contract_Expiration_Date__c = date.newinstance(2017,03,01), AccountId = a.id,
                     StartDate = date.newinstance(2016,03,01));
        insert c;
       Compensation__c cc1 = new Compensation__c(Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'January',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),01,01));
        insert cc1;
        Compensation__c cc2 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'February',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),02,01));
        insert cc2;
        Compensation__c cc3 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'March',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),03,01));
        insert cc3;
        Compensation__c cc4 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'April',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),04,01));
        insert cc4;
        Compensation__c cc5 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'May',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),05,01));
        insert cc5;
        Compensation__c cc6 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'June',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),06,01));
        insert cc6;
        Compensation__c cc7 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'July',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),07,01));
        insert cc7;
        Compensation__c cc8 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'August',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),08,01));
        insert cc8;
        Compensation__c cc9 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'September',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),09,01));
        insert cc9;
        Compensation__c cc10 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'October',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),10,01));
        insert cc10;
        Compensation__c cc11 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'November',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),11,01));
        insert cc11;
        Compensation__c cc12 = new Compensation__c (Payment_Amount__c = 1000.00,Payment_Frequency1__c = 'Annually',
                                          Frequency_Months__c = 'December',Contract__c = c.id, Payment_Amount1__c = 1000.00,Payment_Due_Date__c = date.newinstance(cd.year(),12,01));
        insert cc12;
        System.assert(cc12.Payment_Amount1__c==1000.00 );
Hello,

i have a problem testing my Roll-Up Trigger. Here it is:
 
@isTest(SeeAllData=true)
public class TrgTractorFleetSizeRollupTest {
    static testmethod void validateUploadNewAccount(){
        Account a1 = new Account(Name = 'A1');
        insert a1;
        Account a1a1 = new Account(Name = 'A1A1', ParentId = a1.id);
        insert a1a1;
        Account a1a1a1 = new Account(Name = 'A1A1A1', ParentId = a1a1.id, SoldUnits__c = 125);
        insert a1a1a1;
        Account a1a1a2 = new Account(Name = 'A1A1A2', ParentId = a1a1.id, SoldUnits__c = 125);
        insert a1a1a2;
        System.debug([SELECT Id, SoldUnits__c from Account Where Name = 'A1A1'][0]);
        Account a1a2 = new Account(Name = 'A1A2', ParentId = a1.id);
        insert a1a2;
        Account a1a2a1 = new Account(Name = 'A1A2A1', ParentId = a1a2.id, SoldUnits__c = 100);
        insert a1a2a1;
        Account a1a2a2 = new Account(Name = 'A1A2A2', ParentId = a1a2.id, SoldUnits__c = 90);
        insert a1a2a2;
        System.debug([SELECT Id, SoldUnits__c from Account Where Name = 'A1A2'][0]);
        System.debug(a1a2.SoldUnits__c);
        System.assertEquals([SELECT Id, SoldUnits__c from Account Where Name = 'ss'][0].SoldUnits__c, 450);
    }
}

It doesnt update the value SoldUnits__c  at Account 'A1' which is the grandparent Account.
Any Idea?

Thanks
Peter
Hi,  Could you please help me with the below Apex trigger. I am new to coding and SFDC as well .I am not sure what went wrong. Here is my code  
Contact-lookup with case(Case_c)
Caselookup with Opportunity (Opportunity_c)and Contact(contact)
Opportunity lookup with Contact(contact_c)  
Whenever I update case_c field in Contact,it should update case object and its related opportunity  (I mean the lookup field should be updated with contact name automatically)
 trigger Contacttriggertoupdatecase1 on Contact (before update) { Set<Id> contactids=new Set<Id>(); Map<Id,case> oppcase=new Map<Id,case>(); for(contact CON:Trigger.new) { contactids.add(con.id); }  List<contact> conlist=[Select Id,FirstName,Name,case__r.id from contact where Id IN:contactids]; List<case> caselist=[Select Id,contactid from case where contactId IN: contactids];  if(Caselist.size()>0) { for(Integer i=0;i<caselist.size();i++) { if(Trigger.isbefore&&Trigger.isupdate) { if(Trigger.New[i].case__c!='NULL') { Caselist[i].contactid=Trigger.New[i].id; } } } } //Child Parent SOQL query to retrieve its related opportunity List<case> caseopplist=[Select Id,caseNumber,Opportunity__r.id from Case where id IN:caselist]; for(case co:caseopplist) { //Adding case and its related opportunity id in Map oppcase.put(co.Opportunity__r.id,co); } //Querying related opportunities List<opportunity> opplisttoupdate=[Select id,contact__c from opportunity where id in:oppcase.keyset()];  if(opplisttoupdate.size()>0) {  for(contact con:Trigger.New) { for(opportunity o:opplisttoupdate) { o.contact__c =Trigger.New[0].id; o.contact__c=con.id; //opplisttoupdate[l].contact__c =Trigger.new[l].id; opplisttoupdate.add(o); } } update opplisttoupdate; } }  Regards,
Hello!  I have to deactivate a Trigger as it is blocking a deployment.

I deactivated the Trigger in the sandbox, created a Change Set, included the Trigger in the change set and deployed the same into the Production, but it wasn't able to pass the Apex Test. 

This is the error message that I got:
  • System.Exception: Assertion Failed 
  • Stack Trace: Class.test_updatecontactrolecount.testcreateopptywithconditionandrole: line 38, column 1

I know the problem is with this code "System.assert(false);" but I am not a developer so I don't know how to fix it. I have searched around for solutions but it is way beyond my knowledge.

Can anyone kindly help and let me know how to fix this Apex Test Class? It would be much much appreciated!

The Apex Trigger
trigger 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; 
}
}

The Apex Test Class
public class test_updatecontactrolecount
{
 public static testMethod void testcreateopptywithconditionandrole()
{
//Insert Opportunities 
try
{
    Opportunity Oppty = new Opportunity(Name='Oppty_test1',StageName='Stage 1 - Unqualified Prospect',Type ='New Business', 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 ='Business User',OpportunityId=Oppty.id ,Contactid = cont[0].id ,Isprimary = True),
    new OpportunityContactRole(Role ='Business User',OpportunityId=Oppty.id ,Contactid = cont[0].id ,Isprimary = False)
    };
    insert ocr;    
    Oppty.StageName = 'Stage 3 - Eval Request';    
    //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);
}        
} 
}
Sincerely,
Tina




Sincerely,
Tina
Here is the code I am working with.  I am already at 15 relationship on the Opportunity Object otherwise I would do this with a formula field.

trigger SetPrimaryContactEmail on Opportunity (before insert, before update) {
  Set<ID> setConIds = new Set<ID>();
    for(Opportunity obj : trigger.new)
   {
         if(obj.Primary_Contact__c != null)
            setConIds.add(obj.Primary_Contact__c);
   }

  MAP<ID , Contact> mapCon = new MAP<ID , Contact>([Select Email from Contact where id in: setConIds]);

   for(Case obj : trigger.new)
   {
        if(obj.Primary_Contact__c != null)
          {
            Contact c = mapCon.add(obj.Primary_Contact__c);
            obj.Primary_Contact_Email__c = c.Email;
          }
       
   }
}

Hi, we have a situation where a customer is stating that the workflow rules and alerts where working some way and we believe is technically imposible, however need to confirm this.

Scenario: 
Object: Opportunity
Deposit_deadline__c = formula field that takes the deposit deadline from related Trip object.
npe01__Payments_Made__c = currency field

Object: Trips
Not_Alerts__c = checkbox field
Deposit_Deadline__c = date field

Workflow Criteria (in opportunity object):
AND( (TODAY() + 7 ) == Trip__r.Deposit_Deadline__c , npe01__Payments_Made__c != Amount,Trip__r.Not_Alerts__c = False)

If I edit the opportunity to comply with the rule criteria, and lets say the the deposit deadline is 7 days from now, the rulle will trigger or create the time trigger to trigger an alert for tomorrow or immediatelly (depending on how I have set it up). However, customer states that the deposit deadline date, if set for, lets say 7 days from next friday, then the alert will trigger on Friday, automatically, without having someone go and edit the opportunity.

I believe this is technically impossible, due that the alerts will trigger based upon creation or upon editing a trigger. Is it possible that if a rule today does not comply with rule criteria, but tomorrow does comply because date has changed for that time, triggers the alert? Or is it exctriclty necessary that a user has to edit or create the opportunity?

How would you recommend on setting payment reminders on Salesforce? I think with workflows it may not be possible.

I think there is a related idea on this:

https://success.salesforce.com/ideaView?id=08730000000kymqAAA

Thanks for your help.

Hi everyone - I have a set of about 13,000 records for which I want to update a field using a trigger that I've recently deployed.  Are their any best practices that dictate the best way to "update" that many records?
I'm trying to add a Visualforce map that will display the location of all contacts related to the same account, but I want to add the map to the contact record.  In other words, whenever I view a contact record I'd like to also see the location of not only that account, but of all other contact related to that same account.  

I'm pretty sure I need a custom contoller to make this happen, and while I've started to try to piece one together I'm stuck on the logic that will pull only the contacts related to the same account as the contact currently being viewed.  Hope that makes sense.

Controller:
public with sharing class relConController{ 

    Map<Id,Contact> relCont = new Map<Id,Contact>([SELECT Id,AccountId FROM Contact WHERE Id = :ApexPages.currentPage().getParameters().get('Id')]);
    
    public List<Contact> Records {get; set;} 
    public List<Contact> CurrentRecord {get; set;}
    
    public relConController(){ 
        Records = [select Name, Id, AccountId, MailingStreet, MailingCity, MailingState from Contact]; 
        CurrentRecord = [select Name, Id, MailingStreet, MailingCity, MailingState from Contact WHERE ID = :ApexPages.currentPage().getParameters().get('Id')]; 
    }
}

Page:
<apex:page Controller="relConController">

  <!-- This page must be accessed with an Account Id in the URL. For example: 
       https://<salesforceInstance>/apex/NearbyContacts?id=001D000000JRBet -->
  
  <apex:pageBlock >
    
      <apex:map width="600px" height="400px" mapType="roadmap" zoomLevel="10" center="{!CurrentRecord[0].MailingStreet},{!CurrentRecord[0].MailingCity},{!CurrentRecord[0].MailingState}">
      
        <apex:repeat value="{!Records}" var="Record">
        
            <apex:mapMarker title="{! Record.Name }" position="{!Record.MailingStreet},{!Record.MailingCity},{!Record.MailingState}"/>
            
        </apex:repeat>
        
      </apex:map>
      
  </apex:pageBlock>

</apex:page>


 
Hello,
I am trying to get the recordId in another component. Therefore I wrote a extra Apex method but I am not sure how to get the recordId there. 

Here I need to have the recordId of a Contact to get the right data
/**
   * Returns a case by its ID
   *
   * @param      id    The identifier
   *
   * @return     The case.
   */
  @AuraEnabled
  public static Case getCaseWithContact(Id id) {
    return [
      SELECT
        Id,
        Contact.Name,
        Contact.LastName,
        Contact.FirstName,
        Contact.MailingStreet,
        Contact.MailingCountry,
        Contact.Country_ISO_3166_2__c,
        Contact.MailingPostalCode,
        Contact.MailingCity,
        Contact.Phone,
        Contact.MobilePhone,
        Contact.Fax,
        Contact.Email,
        Contact.CustomerNumberNav__c,
        Contact.CustomerNumberSF__c,
        Contact.SalutationNavisionExport__c
        FROM Case WHERE Id = :id

    ];
  }

I tryed to create a method that gets the recordId and then give it to the getCaseWithContact like:
 
@AuraEnabled
  public static String getIdFromContactInCaseString(Id id) {

    List <case> ownerIdRec = [SELECT VehicleOwner__c FROM Case WHERE Id = :id];

    String ownerIdRecord = ownerIdRec[0];

    return ownerIdRecord;

  }

But there I get the Error Illegal assignment from Case to String.

Can someone help me or give me a tipp?
 
/***ERROR Message
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger ven.IdenticalOpp9 caused an unexpected exception, contact your administrator: ven.IdenticalOpp9: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ven.LeadingCompetitor: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.ven.LeadingCompetitor: line 34, column 1: []: Trigger.ven.IdenticalOpp9: line 32, column 1

*/
/*Write a trigger that creates 10 identical Opportunities whenever an Account with more than 99 employees is created. 
Make sure all Opportunities are associated with the Account. 
Use any values for the fields on the Opportunities*/

  trigger IdenticalOpp9 on Account(after insert){
 
      List<Opportunity> opplist= new List<Opportunity>();

     
        for(Account ac:Trigger.new){
        
               if(ac.NumberOfEmployees>99){
       
                     for(integer count=0;count<10;count++){
       
                        Opportunity opp=new Opportunity();
                          opp.AccountId=ac.id;
                               opp.Name='Created from account';
                          opp.StageName='Prospecting';
                          opp.CloseDate=Date.toDay();
                          opplist.add(opp);
                            }
                      }
             else{
             }
         }
       if(opplist!=null){
       insert opplist;

 }
 
}
Working on a page with a repeat section that pulls in Opportunities related to an Account (standard controller). Inside the repeat I need to show the Contact Roles for each given Opportunity listed. So far I am not finding a way to do this. See related VF and extension controller. I am sure this is super simple but I can't figure it out for the life of me. 

Apex:
public class BlueSheetExtension {
    
    public List <Opportunity> WonOpty {get; set;}
    public List <Opportunity> OpenOpty {get; set;}
    public List <Contact> contacts {get; set;}
    public List <OpportunityContactRole> wonOptyRoles {get; set;}
    public List <OpportunityContactRole> openOptyRole {get; set;}
    public String prodlist {get; set;}
    
    
    public BlueSheetExtension(ApexPages.StandardController controller) {
        
        wonOpty = [Select Id, Name, Amount, Owner.Name, StageName, Last_Touch_Date__c, CloseDate, Goal__c, Actions_For_Goal__c, 
                Status_of_Action__c, red_flags__c, risks__c, terms_months__c, auto_renew__c, Auto_Renew_Months__c From Opportunity 
                Where IsWon = TRUE AND AccountId= :ApexPages.currentPage().getParameters().get('id')];
        
       OpenOpty = [Select Id, Name, Amount, Owner.Name, StageName, Last_Touch_Date__c, CloseDate, Goal__c, Actions_For_Goal__c, 
                Status_of_Action__c, red_flags__c, risks__c, terms_months__c, auto_renew__c, Auto_Renew_Months__c From Opportunity 
                Where IsClosed = FALSE AND AccountId= :ApexPages.currentPage().getParameters().get('id')];
           
        
        Contacts = [Select Id, Name, Title, Owner.Name, Buyer_Type__c, Mode__c, Meeting_Frequency__c 
               From Contact Where AccountId = :ApexPages.currentPage().getParameters().get('id')];
        
        wonOptyRoles = [Select Id, OpportunityId, Opportunity.Name, Contact.Name, Contact.Title, Contact.Owner.Name, Contact.Buyer_Type__c, Contact.Mode__C, Contact.Meeting_Frequency__c 
                From OpportunityContactRole where OpportunityId IN 
                (Select Id from Opportunity Where IsWon = TRUE AND AccountId= :ApexPages.currentPage().getParameters().get('id') )];
        
        openOptyRole = [Select Id, OpportunityId, Opportunity.Name, Contact.Name, Contact.Title, Contact.Owner.Name, Contact.Buyer_Type__c, Contact.Mode__C, Contact.Meeting_Frequency__c 
                From OpportunityContactRole where OpportunityId IN 
                (Select Id from Opportunity Where IsClosed = FALSE AND AccountId= :ApexPages.currentPage().getParameters().get('id') )];
    }

}



VF markup:
<apex:page lightningStylesheets="true" standardController="Account" extensions="BlueSheetExtension">
  <div style="text-align: center;"><img src="{!$Resource.EnveraLogo}"/>
    </div>
   <div style="text-align: center; font-size: 150%;">
        Blue Sheet for {!Account.Name}
    </div>
    <apex:sectionHeader title="Section I. Account Summary"/> <!--Basic Account information-->
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:outputField value="{!Account.Name}" label="Account Name:"/>
            <apex:outputField value="{!Account.Owner.Name}" label="Account Owner:"/>         
        </apex:pageBlockSection>
        <apex:pageBlockSection >
            <apex:outputField value="{!Account.Account_Summary__c}" label="Account Summary:"/>       
        </apex:pageBlockSection>
    </apex:pageBlock>  
    	<apex:sectionHeader title="Section II. Current Services"/> <!--Data for this section comes from Closed Won Opportunities only-->
    	<apex:repeat value="{!WonOpty}" var="w">
    		<apex:pageBlock >      
        	<apex:pageBlockSection >
            	<apex:outputField value="{!w.Name}" label="Opportunity Name:"/>
                <apex:pageBlockSectionItem ></apex:pageBlockSectionItem>
            	<apex:outputField value="{!Account.Name}" label="Product:"/>
            	<apex:outputField value="{!w.Amount}" label="Amount:"/>
            	<apex:outputField value="{!w.Owner.Name}" label="Opportunity Owner:"/>
            	<apex:outputField value="{!w.StageName}" label="Stage:"/>
            	<apex:outputField value="{!w.Last_Touch_Date__c}" label="Last Touch Date:"/>
            	<apex:outputField value="{!w.CloseDate}" label="Close Date:"/>
            	<apex:outputField value="{!w.terms_months__c}" label="Terms Months:"/>
            	<apex:outputField value="{!w.Auto_Renew__c}" label="Auto Renew:"/>
            	<apex:pageBlockSectionItem ></apex:pageBlockSectionItem>
            	<apex:outputField value="{!w.Auto_Renew_Months__c}" label="Auto Renew Months:"/>
                <apex:pageBlockSectionItem ></apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem ></apex:pageBlockSectionItem>
            	<apex:outputField value="{!w.Goal__c}" label="Goal:"/>
            	<apex:outputField value="{!w.Actions_For_Goal__c}" label="Actions for Goal:"/>
            	<apex:outputField value="{!w.Status_of_Action__c}" label="Status for Action"/>
            	<apex:pageBlockSectionItem ></apex:pageBlockSectionItem>
            	<apex:outputField value="{!w.Red_Flags__c}" label="Red Flags"/>
            	<apex:outputField value="{!w.Risks__c}" label="Risks"/>
            	</apex:pageBlockSection>
            <apex:pageBlockSection columns="1" title="Buying Influence" ><!--Contact Roles for the related Opportunity -->  
            <!--Data Table used because of repeating section data shenanigans. I don't like it either and I am sure there is a better way-->  
            <apex:dataTable title="Buyer Influence" value="{!WonOptyRoles}" var="wor"  rules="rows" style="border-color: #f3f2f2">    
       		 <apex:column >
            	<apex:facet name="header">Name</apex:facet>
            	<apex:outputText value="{!wor.contact.name}" style="display: {!IF(w.id=wor.OpportunityId,'table-row','none')}"/>
       		 </apex:column>
        	<apex:column >
            	<apex:facet name="header">Title</apex:facet>
            	<apex:outputText value="{!wor.contact.title}" style="display: {!IF(w.id=wor.OpportunityId,'table-row','none')}"/>
        	</apex:column>
                <apex:column >
            	<apex:facet name="header">Contact Owner</apex:facet>
            	<apex:outputText value="{!wor.contact.owner.name}" style="display: {!IF(w.id=wor.OpportunityId,'table-row','none')}"/>
        	</apex:column>
                <apex:column >
            	<apex:facet name="header">Buyer Type</apex:facet>
            	<apex:outputText value="{!wor.contact.Buyer_Type__c}" style="display: {!IF(w.id=wor.OpportunityId,'table-row','none')}"/>
        	</apex:column>
                <apex:column >
            	<apex:facet name="header">Mode</apex:facet>
            	<apex:outputText value="{!wor.contact.Mode__c}" style="display: {!IF(w.id=wor.OpportunityId,'table-row','none')}"/>
        	</apex:column>
                <apex:column >
            	<apex:facet name="header">Meeting Frequency</apex:facet>
            	<apex:outputText value="{!wor.contact.Meeting_Frequency__c}" style="display: {!IF(w.id=wor.OpportunityId,'table-row','none')}"/>
        	</apex:column>
            </apex:dataTable>
            </apex:pageBlockSection>
            </apex:pageBlock>
    	</apex:repeat>

Fairly new to dev/apex. Just looking for some advice on how to start/structure my trigger as I'm struggling to get it started. 

We want to send emails when Sales Invoices are overdue, to an email address on the related Account (related via lookup from invoice to account). My first thought was to create the trigger from the Account, but can I access the records related via the lookup on Sales Invoice? I couldn't get the SOQL statement working, so thought to do it from Sales Invoice, but that makes no sense as I need to group the Sales Invoices together where there are more than one overdue for each account, which happens more than not. 

Any sugegstions greatly appreciated! 

Hi everyone,

could you please check and help me out
List<case> scope=new List<Case>([select id from case]);
Schema.SObjectType sObjectType = scope.getSObjectType();
String s=(string)sObjectType;
its not working
  • November 17, 2018
  • Like
  • 0
Hey Guys,

I'd like to do something that probably isn't possible but I was directed here from the generic help site so here it goes.

I have a custom Multi Select Picklist with values that are populated from a Global Set. What I would like to do is be able to populate the MSP on the Account and Contact Layouts with extra (already defined) entries when uploading new data with the Import Wizard.

e.g. If we met someone at a tradeshow, entered their data in March and then met them again at a different tradeshow in September, when I upload the new CSV with the new tradeshow picklist value the old one doesn't get overwritten but the new one is added into the field.

I hope that makes sense and, as a fun added caveat, I have absolutely no programming/developing experience so if it is possible please explain it to me like I'm five.

Thanks!
Hi All,

I am trying to get the functionalty(What is the functionality for this batch class).Please someone help me understandig the below code

global class BatchCreateScheduleLineBySOItem implements Database.batchable<sObject>{

    global Database.QueryLocator start(Database.BatchableContext BC){
      List<User> users = [Select u.Id From User u where name=:ScheduleLineHelper.userIntegrationIservice];
      //return all SO Item that not yet have schedule line for all user execept user Integration i:service
      if(users.size()>0){
          String id=users.get(0).Id;
          return Database.getQueryLocator('select Id, Name, CurrencyIsoCode, Item_Qty__c, SalesOrderId__c, Confirmed_Delivery_Date__c,'+ 
            'RequestedDeliveryDate__c from SalesOrderItem__c where Id not in (select SalesItem__c from SalesItemDistribution__c) and CreatedById<>:id');
      }
      //return all SO Item that not yet have schedule line for all user
      return Database.getQueryLocator('select Id, Name, CurrencyIsoCode, Item_Qty__c, SalesOrderId__c, Confirmed_Delivery_Date__c,'+ 
            'RequestedDeliveryDate__c from SalesOrderItem__c where Id not in (select SalesItem__c from SalesItemDistribution__c)');
   }
   
   global void execute(Database.BatchableContext BC, List<sObject> scope){
        //create Schedule Line by all SO Item that not yet have Schedule Line 
        List<SalesItemDistribution__c> lstScl=new List<SalesItemDistribution__c>();
        for(Sobject so:scope){
            SalesOrderItem__c soitem=(SalesOrderItem__c)so;
            SalesItemDistribution__c sc=new SalesItemDistribution__c(Name=soitem.Name, CurrencyIsoCode=soitem.CurrencyIsoCode, 
                                        QuantityConfirmed__c=soitem.Item_Qty__c, SalesDoc__c=soitem.SalesOrderId__c, SalesItem__c=soitem.Id);
                                        
            sc.DateConfirmed__c=(soitem.Confirmed_Delivery_Date__c==null)?
                                soitem.RequestedDeliveryDate__c:soitem.Confirmed_Delivery_Date__c;
                                
            lstScl.add(sc);
            
        }
        insert lstScl;
    }

   global void finish(Database.BatchableContext BC){
   }
   
}

Thanks in Advance
I am trying to write a trigger to do the following.. 

I have a custom object called Project with the API Name of - pse__Proj__c
I have another custom object called Budget with the API Name of - pse__Budget__c

What I want to do with the trigger is.. 

When a new project is created I want the project name to automatically fill a field on the budget object called project. The project field on the budget object is a lookiup field to the project object and has the API name of pse__Project__c. 

Later on I want to also incorporate the trigger to update a field on the budget object called Amount, that has the API name of 
pse__Amount__c with the value found on the Project object in the field called Prouct Budget MAP with the API name of Product_Budget_MAP__c. That can wait but I do need the first step implemented in order to move forward. 

HERE IS WHAT I HAVE SO FAR... Any help is much appreciated!! 


trigger updateBudgetProject on pse__Budget__c (after insert){
    
    List<pse__Budget__c> BudgetToUpdate = new list<pse__Budget__c>();
    
    for(pse__Budget__c bud : [select Id, pse__Proj__c.Id From pse__Budget__c Where Id IN : trigger.newMap.keyset()]){
        bud.pse__Project__c = bud.pse__Proj__c.name;
        BudgetsToUpdate.add(bud);
       }
    
    if(!BudgetsToUpdate.isEmpty())
        update BudgetsToUpdate;
I have a test class that is giving me an error I've never seen before. When I try to send it over to my production org via outbound change set and then validated it via inbound change set I receive the error below.
 
System.DmlException: Insert failed. First exception on row 0; first error: ENTITY_IS_DELETED, entity is deleted: [] 
Stack Trace: Class.Test_YushProdFileUpload.testAttachments: line 38, column 1


My test class is also below. any help i can get wuold be appreciated. 
 
/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class Test_YushProdFileUpload {

    static testMethod void testAttachments()
    
    
    {
      Yushin_Product__c ypd=new Yushin_Product__c(Discharge_Direction__c='Clamp Traverse');
        
        ypd.Opportunity__c='0063900000rYAez';
        ypd.Account__c ='0013900001dOm8T';
        ypd.Discharge_Direction__c='Clamp Traverse';
        ypd.IMM_Mfr__c='Arburg';
        ypd.IMM_Model__c='NT450';
        ypd.Plant_Voltage__c='110';
        ypd.Interface_Voltage__c='110 VDC';
        insert ypd;
        
        ypd.Opportunity__c='0063900000rYAez';
        ypd.Account__c ='0013900001dOm8T';
        ypd.Discharge_Direction__c='Clamp Traverse';
        ypd.IMM_Mfr__c='Engel';
        ypd.IMM_Model__c='110t';
        ypd.Plant_Voltage__c='110';
        ypd.Interface_Voltage__c='110 VDC';
        update ypd;
        
        VRController_YProdFileUpload controller=new VRController_YProdFileUpload(new ApexPages.StandardController(ypd));
 
      controller.fileName='Unit Test Attachment';
      controller.fileBody=Blob.valueOf('Unit Test Attachment Body');
        controller.uploadFile();
      
      List<Attachment> attachments=[select id, name from Attachment where parent.id=:ypd.id];
      System.assertEquals(1, attachments.size());
    }
}

 
  • September 21, 2018
  • Like
  • 0
Hi ,

Here is the trigger  im getting 57% code coverage.Commented area in trigger is not getting covered ,Below is the test class.
For(Opportunity svp:trigger.new) 
        {
            if(svp.Generate_Payment_Schedule__c== true) 
            {
            /*   for(Payment_Schedule_Template__c P:PSTList) 
               
                {
                  system.debug('*************************PS'+PSTList);
                taxlist = [select id,Name from Tax_Master__c WHERE Name='GST' OR  Name= 'Vat & Stax'];
                   system.debug('TTTTTTTTTTTTTTTTAXLIST'+taxlist);
                    for(Tax_Master__c tm:taxlist)
                    {
                    taxid=tm.id;
                    taxName=tm.Name;
                  }
                   system.debug('TTTTTTTTTTTTTTTTAXID'+taxid);
                   // Prec+=P.Percentage__c; 
                   if(taxName=='GST')
                   { 
                PSList.add(new Schedule__c(Display_Order__c = P.Display_Order__c,
                                           Name = P.Name,
                                          Cumulative_Percentage__c=p.Cumulative_Percentage__c,
                                           Cumulative_Installment_Amt__c=p.Cumulative_Percentage__c/100*svp.Total_Agreement_Value__c,
                                           Percentage__c = P.Percentage__c,
                                           Tentative_Due_Date__c=p.Tentative_Due_Date__c,
                                           Installment_Amount__c=p.Percentage__c/100*svp.Total_Agreement_Value__c,                                               
                                           Opportunity__c = myatd[1],
                                           Tax_Master__c = taxid
                 
                                           )); 
                     }
                     else if(taxName=='Vat & Stax')
                     {
                      PSList.add(new Schedule__c(Display_Order__c = P.Display_Order__c,
                                           Name = P.Name,
                                           Cumulative_Percentage__c=p.Cumulative_Percentage__c,
                                           Cumulative_Installment_Amt__c=p.Cumulative_Percentage__c/100*svp.Agreement_Value__c,
                                           Percentage__c = P.Percentage__c,
                                           Tentative_Due_Date__c=p.Tentative_Due_Date__c,
                                           Installment_Amount__c=p.Percentage__c/100*svp.Agreement_Value__c,                                               
                                           Opportunity__c = myatd[1],
                                          // Cumulative_Percentage__c=Prec,
                                           Tax_Master__c = taxid
                 
                                           )); */
                     
                     }    
                                        
             
                      
                  
                   }                                           
                }
                 
                  
            }
           
        
           
         insert PSList;
        PSList.clear();
        PSTList.clear();
        ut.clear();
       myatd.clear();  
       } 
    }
 
static testMethod void ScheduleTest() 
    {
        Tax_Master__c tm = new Tax_Master__c(Name='GST');
        insert tm;
        Account a = new Account(name='Ravi');
        insert a;
        
        
        Project__c pr = new Project__c(Name='Laplazzo');
        insert pr;
        Block__c b = new Block__c(Name='block one',Project_Name__c=pr.id);
        insert b;  
         Apartment__c ap = new Apartment__c(Name='112', Block__c=b.Id, Status__c='Available');
        insert ap;
        
        List<Payment_Schedule_Template__c> PSTList = new List<Payment_Schedule_Template__c>();
        for (integer i = 1; i <10; i++)
        {
        PSTList.add(new Payment_Schedule_Template__c(
                    Name = 'Payment schedule One', Percentage__c = 0.00, Block__c = b.id,
                    Tentative_Due_Date__c = System.Today(),Display_Order__c = i));            
        }
        Insert PSTList;
       
        Opportunity o=new Opportunity(Name='raviopp',AccountId=a.Id,StageName='Blocking', Apartment__c =ap.id,CloseDate=Date.today(), Generate_Payment_Schedule__c = True);
        insert o;   
        system.debug('OPPPPPPPPPPPP'+o);
        if(o.Generate_Payment_Schedule__c)
        {
        system.debug('OOOOOOOOOOOOOOOOO'+o.Generate_Payment_Schedule__c);
            List<Payment_Schedule_Template__c> PSList = new List<Payment_Schedule_Template__c>();
            for (Payment_Schedule_Template__c P: PSTList)
            {
            system.debug('PPPPPPPPPPSTLIST'+PSTList);
            Tax_Master__c tm1 = new Tax_Master__c(Name='GST');
             insert tm1;
             Schedule__c sch= new Schedule__c(Display_Order__c=1,Name='sch1',Cumulative_Percentage__c=0.06,Tentative_Due_Date__c=System.Today(),Opportunity__c=o.id);
             insert sch;
            PSList.add(new Payment_Schedule_Template__c(
                      Name = P.Name,Block__c=b.id,Percentage__c = P.Percentage__c,
                      Tentative_Due_Date__c = System.Today(), Display_Order__c = P.Display_Order__c));
            }
            Insert PSList;
            update PSList;
        }
         update o;
   }    
}
Pls help me to resolve this .
 
  • September 15, 2018
  • Like
  • 0
Hey Guys, I have a requirement where I have to bulk insert around 3000 records into a table every Saturday. This will be done using a batch job. After insertion, I have to update the Rank fields of the records based on a Revenue field while grouping it by Region and Team.
The logic is pretty simple, create a list of all the records, order by revenue DESC, loop through the list and use the index as the ranking.

However, I'm hung up on doing this at a large scale. It can't be done through a trigger since it gives me a 10,001 DML error. I've tried Apex Batch Update, but that seems to only load 200 records at a time before applying the above logic. However, I need to run the logic on all the records at once. I'm not very familiar with Batch Apex so maybe there is a different way to load the data.

How can this be done? Thankyou.
I have a problem with Account trigger afterupdate event. Below are the problem details. 

Expectation is: Whenever I update a Status column in Account, there is a method in AfterInsertUpdate in trigger which updates the status of custom objects related to Account(child objects)

Problem is : Whenever I update the Status column in Account, trigger fires and executes upto BeforeUpdate event and executes all the methods which are being called in Beforeupdate event. But after this I see in Debug log that some validation fires and after that again BeforeUpdate event starts and I see that oldmap no longer hold the status to which I updated the Account. i.e. oldmap and new values are same, which results in my condition in IF statement not meeting and hence update is not happening. 

Actions Taken: 
1. 
I commented the all the methods step by step being called in Before update and checked the logs but no luck. 
2. I Inactivated all update workflows related to Account and checked but no luck again

Thanks in Advance for your help. 

Trigger:
trigger IS_AccountTrigger on Account (after insert, after update, before insert, before update, before delete, after delete) {
    system.debug('reached insisde trigger');
    ISecG_Trigger_Settings__c objTriggerSetting = ISecG_Trigger_Settings__c.getInstance();
   
    
   if(objTriggerSetting.Enable_Account_Trigger__c) {
        if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)) {
            system.debug('reached inside after trigger');
            IS_AccountTriggerHandler.afterInsertUpdate();     \\MY METHOD IS BEING CALLED FROM HERE
             if(trigger.isInsert){             
            <CustomClass.CustomMethod>(Trigger.new,Trigger.oldmap); 
             }
        }
        if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
            system.debug('reached insisde before trigger@@@@@');
            IS_AccountTriggerHandler.beforeInsertUpdate();
         }
        if(trigger.isInsert && trigger.isBefore) {
            IS_AccountTriggerHandler.beforeInsert();
        }
        if(trigger.isBefore && trigger.isUpdate) {
            IS_AccountTriggerHandler.beforeUpdate();
         }
        if(Trigger.isBefore && Trigger.isDelete) {
            IS_AccountTriggerHandler.beforeDelete();
            <CustomClass.CustomMethod>(Trigger.old); 
      }
        if(Trigger.isAfter && Trigger.isDelete) {
            IS_AccountTriggerHandler.afterDelete(Trigger.old);
           }
        }
   }
public class updateNameClass{
   // public String updateValue{get;set;}
    public updateNameClass(ApexPages.Standardcontroller controller){
    } 
    public PageReference gotostep2(){
        PageReference pref2=New PageReference('/apex/step2page');
        pref2.setRedirect(True);
        return pref2;
    }
    public List<Opportunity>optyList{set;get;}
    public  Map<String, String>labelToAPIName {set;get;}
    public String fldValue {set;get;}
    public List<Opportunity>optyUpdate{set;get;}
    public updateNameClass(ApexPages.StandardSetcontroller controller){
        this.optyList=(List<Opportunity>)Controller.getRecords() ;
        labelToAPIName = new Map <String, String> ();
        
        Map<String, Schema.SObjectField>fieldsMap = Schema.SObjectType.Opportunity.fields.getMap();
        for (Schema.SObjectField field :fieldsMap.values())
        {
          //  System.debug('label'+field.getDescribe().getLabel()+'*********Api**********'+field.getDescribe().getName());
            labelToAPIName.put(field.getDescribe().getLabel(), field.getDescribe().getName());
        }
    }
    
    public pageReference updateMethod(){
        optyUpdate=new List<opportunity>();
        
        String fld = System.currentPageReference().getParameters().get('fieldName');
        System.debug('fld'+fldValue+'==='+fld); 
        if(labelToAPIName.containsKey(fld)){
            String apiFld=labelToAPIName.get(fld);
            System.debug('api'+apiFld);
            for(opportunity op:optyList){
                Map<String, Object>fieldValueMap = new Map<String, Object>();
                fieldValueMap.put(apiFld,fldValue );
                op.put(apiFld,fldValue);
                optyUpdate.add(op);
            }                         
        } 
        Update(optyUpdate);
        System.debug('optyUpdate'+optyUpdate);
        PageReference pref2=New PageReference('/apex/oppupdatepage');
        pref2.setRedirect(True);
        return pref2;
    }     
}

when i give a new value for a field it should be updated in all records(Mass update records from list view). its updating for string fields but not for other fields like date, boolean, decimal etc. Can anyone help me on this? Thanks in Advance!
Hi,
So this trigger autoconverts a lead into a person account when they come in without the company field populated, and becuase it gets conceted into aperson account, it creates a contact & account & opportunity. We don't want it to create an opportunity, so how would I go about doing this with my trigger? or would I have to create a new one? 
Trigger AutoConvert on Lead (after insert) {
     LeadStatus convertStatus = [
          select MasterLabel
          from LeadStatus
          where IsConverted = true
          limit 1
     ];
     List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();

     for (Lead lead: Trigger.new) {
          if (!lead.isConverted && lead.Company == null) {
               Database.LeadConvert lc = new Database.LeadConvert();
               String oppName = lead.Name;
               
               lc.setLeadId(lead.Id);
               lc.setOpportunityName(oppName);
               lc.setConvertedStatus(convertStatus.MasterLabel);
               
               leadConverts.add(lc);
          }
     }

     if (!leadConverts.isEmpty()) {
          List<Database.LeadConvertResult> lcr = Database.convertLead(leadConverts);
     }
}

Any help is much appreciated!!!

Many Thanks :)
Natasha
Hi All- with the help of this group, I wrote the below trigger and test class. The trigger is run on the camp members object. it calculates the unique members whose accounts are tagged as SQA. For example a campaign can have 50 members for 10 accounts. 5 of these accounts are tagged as SQA and I want that count of 5 shown on the Campaign. The test class passed in SB and I got a code coverage of 76%. when I tried to push to prod I get the error below

System.AssertException: Assertion Failed: Expected: 1, Actual: null 
Stack Trace: Class.UniqueSQAsTest.testCampaignWithSQA: line 54, column 1

my trigger and class below. Any help how to fix will be much appreciated 

Trigger
 
trigger UniqueSQAs on CampaignMember (after Insert, after Update, after Delete, after UnDelete) {
    List<Id> campaignIds = new List<Id>();
 
    if(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete) {
        for(CampaignMember member : Trigger.New) {
            if(member.CampaignId != null && member.ContactId != null && member.Account_ID__c != null && member.SQA_Org__c  == true) {
                campaignIds.add(member.CampaignId);
            }
        }
    }
    
    if(Trigger.IsDelete) {
        for(CampaignMember member : Trigger.Old){
            If(member.CampaignId != null && member.ContactId != null && member.Account_ID__c != null && member.SQA_Org__c  == true) {
                campaignIds.add(member.CampaignId);
            }
        }
    }
 
    // Get a list of Campaigns
    Map<ID,Campaign> campaignsOriginalMap = new Map<ID, Campaign>([SELECT ID, Sum_of_unique_SQAs__c FROM Campaign WHERE Id = :campaignIds]);
    
    // Get a list of CampaignMembers
    List<CampaignMember> campaignMembersLst = [SELECT Id, Account_ID__c, ContactId,CampaignId FROM CampaignMember WHERE CampaignId = :campaignIds AND SQA_Org__c  = true];
    
    // Loop round and remove elements that don't has a ContactId or Account_Id__c populated
    for(Integer i=0; i < campaignMembersLst.size(); i++){
         if(campaignMembersLst.get(i).ContactId == null || campaignMembersLst.get(i).Account_ID__c == null) {
             campaignMembersLst.remove(i);
         }
     }
    
    // Duplicate Account removal...
    Map<Id,CampaignMember> accountIdToCampMemberMap = new Map<Id,CampaignMember>();
    for(CampaignMember memRec : campaignMembersLst){
        if(!accountIdToCampMemberMap.containsKey(memRec.Account_ID__c)){
            accountIdToCampMemberMap.put(memRec.Account_ID__c,memRec);
        }
    }
    
    //Create a map of campaigns to be updated
    Map<Id,Campaign> campaignsToBeUpdatedMap = new Map<Id,Campaign>();
   
    //Iterate through the unique campaign members and add up the unique_SQAs to corresponding campaign
    for(CampaignMember membRec: accountIdToCampMemberMap.values()){
        if(campaignsToBeUpdatedMap.containsKey(membRec.CampaignId)){
            Campaign campaignRec = campaignsToBeUpdatedMap.get(membRec.CampaignId);
            campaignRec.Sum_of_unique_SQAs__c = campaignRec.Sum_of_unique_SQAs__c + 1;
        }else{
            Campaign campaignRec = campaignsOriginalMap.get(membRec.CampaignId);
            campaignRec.Sum_of_unique_SQAs__c = 1;
            campaignsToBeUpdatedMap.put(membRec.CampaignId,campaignRec);
        }
       
    }
   
    try {
        if(campaignsToBeUpdatedMap.size() > 0) {
            update campaignsToBeUpdatedMap.values();
        }
    }
    catch(Exception e) {
        system.debug('Thrown Exception for TotalDifferentCompaniesAttached Is: ' + e.getMessage());
    }
}
 
 
Test
 
@isTest
private class UniqueSQAsTest {
   private static testMethod void testCampaignWithSQA() {
    system.debug('Started Member Insert Test Class');
 
    //Start: Test Data Creation
    //Is there any common test data creation class??
   
    //Insert Account
    Account acct = new Account (Name = 'Acme, Inc.',
                                Website ='www.test.com',
                                Type = 'Other',
                                SQA_Categorisation__c='SQA',
                                Region__c = 'APAC',
                                Sub_Region__c ='India');
    insert acct;
    system.debug('Inserted Account, ID: ' + acct.id);
   
    //Insert Contact
    Contact con = new Contact(
                      FirstName = 'Robin',
                      LastName = 'Koehler',
                      AccountId = acct.Id,
                      Title ='COO',
                      Email ='robin@hotmail.com',
                      Phone ='5544789',
                      LeadSource ='Event',
                      contact_type__c='CCM');
    insert con;  
    system.debug('Inserted Contact, ID: ' + con.id);
 
    //Insert Campaign  
    Campaign camp = new Campaign(
                        Name = 'Test',
                        IsActive = TRUE
                        );           
    insert camp;
    system.debug('Inserted Campaign, ID: ' + camp.id);
   
    //Insert CampaignMember  
    CampaignMember member = new CampaignMember(
        ContactId = con.Id,
        Status = 'Sent',
        CampaignId = camp.Id
        );
    insert member;
   
    system.debug('Inserted CampaignMember, ID: ' + member.Id);
   
    Test.startTest();
   
 List<Campaign> campaigns = [SELECT Sum_of_unique_SQAs__c FROM Campaign WHERE Id = :camp.Id];
 
  system.assertEquals(1,campaigns.get(0).Sum_of_unique_SQAs__c);
 
    Test.stopTest();
    //End: Test Data Creation
 
 
   }
}