• Mahmoud Coudsi 1
  • NEWBIE
  • 75 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 32
    Questions
  • 23
    Replies
Overview/context:

I have a new phone system that sync calls summary into Salesforce in a form of tasks. Now I'm developing a trigger that fires each time these tasks (Call summary) are logged with a certain critieria, creating a new tasks on Salesforce based on the call result.

Code:
Trigger AssignTasksBasedOnPhoneTags on Task (After insert) {

    // Create a list that includes all the Tasks
    List<Task> TasksList = new List<Task>();
    
    Task NewestSalesRelatedTask = new Task();
    
    NewestSalesRelatedTask = [SELECT Id, whatid, CallDisposition, whoid
                                 FROM Task 
                                 WHERE CallDisposition LIKE '%Sales inquiries%' AND CallDisposition LIKE '%Call requires a follow-up%'
                                 ORDER BY ActivityDate ASC
                                 LIMIT 1];
                                                        
                                                                            
    if(NewestSalesRelatedTask.CallDisposition.contains('Sales inquiries') && NewestSalesRelatedTask.CallDisposition.contains('Call requires a follow-up')) {
    
    TasksList.add(new Task(subject= 'Alissa: A new lead needs follow up',
                 Description= 'Hey Alissa, based on this lead last call, this need lead need to be followed up with. Please refer to leads previous call',
                 ActivityDate= Date.today().addDays(1),
                 WhatID= NewestSalesRelatedTask.whatid));
    } 
    insert TasksList;
}

Reproduction/Error message:
 
Create any new task manually or the telephony system would lead to this error message. Even when conditition is not met: (CallDisposition LIKE '%Sales inquiries%' AND CallDisposition LIKE '%Call requires a follow-up%')

" Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger AssignTasksBasedOnPhoneTags caused an unexpected exception, contact your administrator: AssignTasksBasedOnPhoneTags: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AssignTasksBasedOnPhoneTags: maximum trigger depth exceeded Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert: []: () "
I keep getting this error message: Error: Compile Error: Expecting ')' but was: 'Red' at line 5 column 16, when I run the following Apex Class: 
public class Test {

Map<String, String> colorCodes = new Map<String, String>();

colorCodes.put('Red', 'FF0000');
colorCodes.put('Blue', '0000A0');

String myColor = colorCodes.remove('Blue');
String code2 = colorCodes.get('Blue');

System.assertEquals(null, code2);

}
What am I missing here?

 
I'm trying to create a field on the account's page layout that captures the lead creation date. Anyone has an idea how to do it? 
 
Hi all,
 
Can anyone help me in solving the scenario below .
 
I have written an onclick javascript button and called a method and passed one arguement into it. Now I want to write a test method for the class which is declared as webservice and load bunch of CSV and JSON data into the class.
 
/////JAVASCRIPT BUTTON CODE////////
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")} 

var msg = new sforce.SObject("Lead"); 
msg.Id = '{!Lead.Id}'; 	

var result = sforce.connection.update([msg]); 

var patientId='{!Lead.Name}'; 
var result = sforce.apex.execute("Qualification","PreQualificationCheck",{patientID: patientId}); 

alert(result); 


// } 

window.location.reload(); 
sforce.debug.trace=true;
 
/////APEX CLASS/////
global with sharing class Qulification {

// API secret key and password


Webservice static void PreQualificationCheck(String patientID) {
             
 // Find the patient in question using the passed in Patient ID through the check Qulification button
     Lead l = [select Id, Name, Leads_DOB__c, FirstName, LastName,
                              From Lead
                              Where Name = :patientID];  

// a series of if-else statements to determine lead qualification (More than 40 scenario
if(bla bla  == bla) {
  ..etc
  ..etc
  ..etc
 }

update l;

}

Private static String getCoverageInformation(String response, String patientID) {

// Parase JSON responses into variables --> then Salesforce fields

// A series of if-else statements to further determine lead qualification

}


Test Class/Method:

To trigger all the possible API reponses in my scenerio, I have 40+ different input possiblities (combinations) that should fire back 40+ responses combinations. Afterwards, the responses go through a series of if-else statements to results in one of the three possible answers. 

Since there are numerous of inputs and outputs in this case are, I thought it would be best to utilize the static resources; load my input data through a CSV (1000+ records) and load another JSON file of all the different possible outputs (API responses). 

I haven't got very far with my test class, as I need more direction here: 

1. How can I call the PreQualificationCheck method and pass my CSV lead data through it?
2. How can I tie in my input data that I'm entering in the class through CSV to the response data that being returned as a JSON from the API response call? Do I actually have rewrite my if-else statements logic in the @testclass? 

Example:

If (State__c == "Texas" &&  Lead_Type__c == "Remote memeber" && Lead_Memeber_Policy_Id == 1234111) {Memeber_Group_type__c = "Commerical" && Active__c = "True"..etc.}

CSV (Input): State__c, Lead_Type__c, Lead_Memeber_Policy_Id
JSON (Output/API response): Memeber_Group_type__c, Active__c
 

@isTest 
global class DataUtil {
    static testmethod void testLoadData() {
        // Load the test lead from the static resource
        List<sObject> ls = Test.loadData(Lead.sObjectType, 'TestCSV');
        
        // Verify that all my 1000 test lead were created
        System.assert(ls.size() == 1000);

        // Get first test lead
        Lead l1 = (Lead)ls[0];
        String LeadFirstName = l1.FirstName;
        String LeadLastName = l1.LastName;
        String PolicyID = l1.Leads_Policy_ID__c;
        Decimal Weight = l1.LEADS_WEIGHT__c;
        Decimal Feets = l1.FEET__C;
        Decimal Inches = l1.INCHES__c;
        
// Now not sure what do I do next? Do I loop through all the 1000 leads and entering as params in the method? 

// How can load my JSON - static resource to load my respones to this test class? (I have a rough idea but detailed description/examplification would be apperciated)

// How can I tie in my input data that I'm entering in the class through CSV to the response data that being returned as a JSON from the API response call? Do I actually have rewrite my if-else statements logic in the @testclass?            

       }
}

Please help me in writting the test method for the above class.

P.S:

My code runs perfectly fine on the sandbox so no need to review the Qulification Class or the Button's code.

I'm trying to write a test class and load bunch of test lead's data but for some reason when I call the static resource (that has my CSV) is not recognizing the custom fields. Example, Lead_insurance_Id__c

My CSV file - static resource:
// Example of how my CSV looks like

Id, Firstname, Lastname, Leads_Insurance_ID__c,..etc

000012, Fares, Alsyoufi, 12184111, ..etc
000011, Fare,syoufi, 12184211, ..etc
000013, Fares, syouf, 12184311, ..etc

My test class:
 
@isTest 
global class DataUtil {
    static testmethod void testLoadData() {
        // Load the test accounts from the static resource
        List<sObject> ls = Test.loadData(Account.sObjectType, 'TestData');
        
       }
}

Error message: 

User-added image

Seems like the standard Salesforce fields didn't cause any execptions but custom fields did (I tried other one beside Lead_Insurance_Id__c) and I still got the same error message. 

P.S:
I've tried to change my CSV header to all of these formats but non helped:

LEADS_INSURANCE_ID__c
Leads_insurance_Id__c
Lead.DLeads_insurance_Id__c
Insurance ID (Field's label)

Hi,

I have an APEX class that is built on the lead object. The class runs multiple methods (Trigger API calls) and if-statments to determine lead qualifcation. I'd like to invoke the class through both a Java button and an Apex Trigger:

1. Here is the code for the check eligibilty Java button:

// This part been implemented first and it worked fine.
 
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}
 
var msg = new sforce.SObject("Lead");
msg.Id = '{!Lead.Id}';
msg.Qualification_message__c = null;
 
var result = sforce.connection.update([msg]);
 
var patientId='{!Lead.Name}';
var result = sforce.apex.execute("Eligibility","PreEligiblityCheck",{MemberID: MemberId});
alert(result);
window.location.reload();
sforce.debug.trace=true;
 

2. Here is the code for the APEX trigger: (This is where the issues started coming up)

Trigger CheckEligiblityUponSelfSchedule on Lead (before update) {
  
  for(Lead l: Trigger.new) {                           
    if(l.self_scheduled__c == TRUE){
    Eligibility.runEligibilityCheck(l.Id);
    }
  }
}
 

3. Here is the error message that I'm getting upon checking the box for self-schedule and saving the lead record:

Error:Apex trigger CheckEligiblityUponSelfSchedule caused an unexpected exception, contact your administrator: CheckEligiblityUponSelfSchedule: execution of BeforeUpdate caused by: System.QueryException: List has no rows for assignment to SObject: Class.Eligibility.buildEligibilityRequest: line 175, column 1

Snippet from runEligiblityCheck method code: 
Public static String runEligibilityCheck(String MemberID) {
       
      // confidential code to make an API call to a third-party tool to determine lead qualification based on a set logic we have set up internally.  
         
    }
Snippet from buildEligibilityRequest method

private static String buildEligibilityRequest(String MemberID) {
        // Find the patient in a query using the name passed in PatientID
// This is line 175 where the code is breaking //
       Lead l = [select Id, Name, Leads_DOB__c, FirstName, LastName, self_scheduled__c
                              From Lead
                              Where Name = :MemberID];
 

Any ideas about this specfic issue that I'm having? Also any ideas if it's possible to execture the same class through a Java-script button and trigger depends on a specific criteria?

Upon saving a lead record I get this error message:

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger CheckEligiblityUponSelfSchedule caused an unexpected exception, contact your administrator: CheckEligiblityUponSelfSchedule: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.CheckEligiblityUponSelfSchedule: line 4, column 1

Any ideas? 

Here is my code:

Trigger CheckEligiblityUponSelfSchedule on Lead (after update) {
  
  for(Lead l: Trigger.new) {    
    if(l.self_scheduled__c = TRUE){
    Eligibility.runEligibilityCheck(l.id);
    }
  }
}
What i'm trying to achive:

Simply call a class from a trigger when checkbox is checked and lead record is saved.

Error message:

Error: Compile Error: Method does not exist or incorrect signature: void runEligibilityCheck() from the type Eligibility at line 4 column 15
 
// My Class

global with sharing class Eligibility {
// Code here
    
      private static String runEligibilityCheck(String patientID) {
      // More code in my method

     }

}
// My Trigger.
Trigger CheckEligiblityUponSelfSchedule on Lead (before update, before insert) {
  for (Lead l: Trigger.new) {
  if(l.self_scheduled__c = TRUE){
  Eligibility.runEligibilityCheck();
    }
  }
}
Error message: "Error: Compile Error: Expression cannot be assigned at line 208 column 36"

Objective: I want to assign two different values to two different fields based on one conditional statement (programmatically) 

Code #1:

The code below works as expected but when I tried to add "&&" in Code #2 the code didn't not run.
 
// Determine coverage 
        
        if (insuranceType == 'BLA') {
             l.Insurance_type__c = 'Bla bla' l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else if(NonAcceptedPlans.contains(groupName)) {
             l.Insurance_type__c = 'Bla bla Bla bla';
        } else if(planDescription == '') {
             l.Insurance_type__c = 'TTT';
        } else {l.Insurance_type__c = 'Bla bla Bla bla Bla bla';}

Code #2:

When adding "&&" to my output part of the conditional statement the code stops working. I get an message: "
Error: Compile Error: Expression cannot be assigned at line 208 column 36"
 
// Determine coverage 
        
        if (insuranceType == 'BLA') {
             l.Insurance_type__c = 'Bla bla' l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else if(NonAcceptedPlans.contains(groupName)) {
             l.Insurance_type__c = 'Bla bla Bla bla' && l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else if(planDescription == '') {
             l.Insurance_type__c = 'TTT' && l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else {l.Insurance_type__c = 'Bla bla Bla bla Bla bla' && l.Qualification_message__c = 'Bla bla Bla blaBla bla";}
Hi,

I have deployed this Apex Testing class in production that messed up my whole production org; it got to a point where I'm not able to deploy anything on production nor able to delete it (the Apex class that's causing the issue). 

Here what I did to delete test class:

1. I download Eclipse and insalled the Foce.com IDE.
2. Then I created Foce.com two projects; one includes all my master production org components and one includes all of my sandbox components.
3. After that I went to sandbox project and altered my class file.xml to "Deleted" and changed four of my triggers (tied to the class, not needed anymore) to "Inactive"
4. I attempted to deploy the five components (referenced above) to production in order to delete trigger and deactive class but I failed. Got this error message and coverage results:
 
*** Deployment Log ***
Result: FAILED
Date: October 17, 2017 5:35:32 PM PDT

# Deployed From:
   Project name: Inbody_replacing
   Username: mahmoud@enarahealth.com.sandbox
   Endpoint: test.salesforce.com

# Deployed To:
   Username: mahmoud@enarahealth.com
   Endpoint: login.salesforce.com

# Deploy Results:
   File Name:    classes/InsertInbodyData_TestClass.cls
   Full Name:  InsertInbodyData_TestClass
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

   File Name:    package.xml
   Full Name:  package.xml
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetInitialPBFValue.trigger
   Full Name:  GetInitialPBFValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetInitialSMMValue.trigger
   Full Name:  GetInitialSMMValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetLatestPBFValue.trigger
   Full Name:  GetLatestPBFValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetLatestSMMValue.trigger
   Full Name:  GetLatestSMMValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

# Test Results:

Run Failures:
  InsertInbodyData_TestClass.UpdateBIA System.DmlException: Update failed. First exception on row 0 with id a076100000HLRd3AAH; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
User-added image

Here is the code for Apex class (InsertInbodyData_TestClass) and one of the triggers (GetInitialPBFValue) (The triggers logic is identical across all four triggers).
 
Trigger GetInitialPBFValue on Inbody__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Inbody__c inbdy : trigger.new) {
        accountIds.add(inbdy.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);

    //SOQL query that returns that latest weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account account : [
            Select Id,
                (
                    SELECT Test_Date_Time__c, Percent_Body_Fat__c
                    FROM Inbody__r
                    WHERE Percent_Body_Fat__c != NULL
                    ORDER by Test_Date_Time__c asc
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store latest weight value 
            Decimal IPBF = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Inbody__r.isEmpty()) {
                IPBF = account.Inbody__r.get(0).Percent_Body_Fat__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_PBF_Value__c = IPBF
               
            ));
                         
        }   
        
        Update accountsToUpdate;
        
        }
      }
GetInitialPBFValue Trigger:
@isTest(SeeAllData=true)
Private class InsertInbodyData_TestClass {

    @isTest static void InsertInbody() {
        Account accnts = new Account();
        Inbody__c BIA = new Inbody__c();
        
        RecordType rt = [SELECT ID,Name FROM RecordType WHERE SobjectType='Account' and Name='Patients' Limit 1];
        
        accnts.name = 'afagas';
        accnts.RecordTypeID = rt.id;
        
        insert accnts;
        
        BIA.Skeletal_Muscle_Mass__c = 200;
        BIA.Percent_Body_Fat__c = 160;
        BIA.Test_Date_Time__c = Date.today();
        BIA.patient__c = accnts.id;
        
        insert BIA;
               
        }
        
    @isTest static void UpdateBIA() {
        Inbody__c BIA = new Inbody__c();
        BIA.id = 'a076100000HLRd3';
        BIA.weight__c = 100;
        BIA.Test_Date_Time__c = date.today();
        BIA.patient__c = '0016100000V5qTw';
        
        update BIA;   
        
        }
     
}
This issue had became a HUGE bottleneck in my development process, any input would be greatly appreciated!





 
Hi,

I have deployed this Apex Testing class in production that messed up my whole production org; it got to a point where I'm not able to deploy anything on production nor able to delete it (the Apex class that's causing the issue). 

Here what I did to delete test class:

1. I download Eclipse and insalled the Foce.com IDE.
2. Then I created Foce.com two projects; one includes all my master production org components and one includes all of my sandbox components.
3. After that I went to sandbox project and altered my class file.xml to "Deleted" and changed four of my triggers (tied to the class, not needed anymore) to "Inactive"
4. I attempted to deploy the five components (referenced above) to production in order to delete trigger and deactive class but I failed. Got this error message and coverage results:
*** Deployment Log ***
Result: FAILED
Date: October 17, 2017 5:35:32 PM PDT

# Deployed From:
   Project name: Inbody_replacing
   Username: mahmoud@enarahealth.com.sandbox
   Endpoint: test.salesforce.com

# Deployed To:
   Username: mahmoud@enarahealth.com
   Endpoint: login.salesforce.com

# Deploy Results:
   File Name:    classes/InsertInbodyData_TestClass.cls
   Full Name:  InsertInbodyData_TestClass
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

   File Name:    package.xml
   Full Name:  package.xml
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetInitialPBFValue.trigger
   Full Name:  GetInitialPBFValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetInitialSMMValue.trigger
   Full Name:  GetInitialSMMValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetLatestPBFValue.trigger
   Full Name:  GetLatestPBFValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetLatestSMMValue.trigger
   Full Name:  GetLatestSMMValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

# Test Results:

Run Failures:
  InsertInbodyData_TestClass.UpdateBIA System.DmlException: Update failed. First exception on row 0 with id a076100000HLRd3AAH; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
Deployement coverage results:

User-added image

Here is the code for Apex class (InsertInbodyData_TestClass) and one of the triggers (GetInitialPBFValue) (The triggers logic is identical across all four triggers).
 
Trigger GetInitialPBFValue on Inbody__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Inbody__c inbdy : trigger.new) {
        accountIds.add(inbdy.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);

    //SOQL query that returns that latest weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account account : [
            Select Id,
                (
                    SELECT Test_Date_Time__c, Percent_Body_Fat__c
                    FROM Inbody__r
                    WHERE Percent_Body_Fat__c != NULL
                    ORDER by Test_Date_Time__c asc
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store latest weight value 
            Decimal IPBF = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Inbody__r.isEmpty()) {
                IPBF = account.Inbody__r.get(0).Percent_Body_Fat__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_PBF_Value__c = IPBF
               
            ));
                         
        }   
        
        Update accountsToUpdate;
        
        }
      }

GetInitialPBFValue Trigger:
 
@isTest(SeeAllData=true)
Private class InsertInbodyData_TestClass {

    @isTest static void InsertInbody() {
        Account accnts = new Account();
        Inbody__c BIA = new Inbody__c();
        
        RecordType rt = [SELECT ID,Name FROM RecordType WHERE SobjectType='Account' and Name='Patients' Limit 1];
        
        accnts.name = 'afagas';
        accnts.RecordTypeID = rt.id;
        
        insert accnts;
        
        BIA.Skeletal_Muscle_Mass__c = 200;
        BIA.Percent_Body_Fat__c = 160;
        BIA.Test_Date_Time__c = Date.today();
        BIA.patient__c = accnts.id;
        
        insert BIA;
               
        }
        
    @isTest static void UpdateBIA() {
        Inbody__c BIA = new Inbody__c();
        BIA.id = 'a076100000HLRd3';
        BIA.weight__c = 100;
        BIA.Test_Date_Time__c = date.today();
        BIA.patient__c = '0016100000V5qTw';
        
        update BIA;   
        
        }
     
}
This issue had became a HUGE bottleneck in my development process, any input would be greatly appreciated!
 
Hello,

I'm new to Salesforce Apex. I keep getting this error message when I try save my code eventhough I've declared the variable already..

User-added image

Compile Error: Variable does not exist: BTLog at line 16 column 33    ​
Trigger AutocreateBTWeightRecordsAndMatchitToAccount on bodytrace__c (after insert) {
    for (BodyTrace__c BTLog : Trigger.new) {
    
    Bodytrace_weight__c BTWeight = new Bodytrace_Weight__c();
 
    BTWeight.IMEI__c             =  BTLog.IMEI__c;
    BTWeight.Weight__c           =  BTLog.Values_weight__c;
    BTWeight.Date_of_reading__c  =  BTLog.CreatedDate;
    BTWeight.bodytrace_log__c    =  BTLog.ID;
         
    Insert BTWeight;
      
    }
    
        For (Account Accnt : Trigger.new) {
            if(accnt.IMEI__c == BTLog.IMEI__c){
            BTWeight.Account__c = account.ID;
            }
        }
}
Background on what I'm trying to do:

I'm trying to build a trigger that create a weight reading records (Bodytrace_Weight__c) based of weight logs records (Bodytrace_Weight__c). After that I'd like to auto-assign (Bodytrace_Weight__c) to the patient who got weighted based on the serial number that is found on both; account object and Bodytrace_Weight__c object.

Please let me know what's the best way to build this. Thanks!
Hello,

High-level problem:

I'm trying to build a caculated filed that returns percent weight loss for patient accounts at 6 weeks mark. I did that through building a trigger and custom filed on the account object. Trigger works for some accounts and throw this error message (below) for other accounts.  

Error mesage return upon saving records:

I keep getting this error message upon saving editing/inserting new appointments (Child/Detail records) for persons account. 

Review all error messages below to correct your data.
Apex trigger ReturnPercentWeightLossAt6WeeksMark caused an unexpected exception, contact your administrator: ReturnPercentWeightLossAt6WeeksMark: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.ReturnPercentWeightLossAt6WeeksMark: line 42, column 1

(Please refer to the end of the page if you want a get a clearer idea of what I'm trying to accomplish by building this trigger)
 
Trigger ReturnPercentWeightLossAt6WeeksMark on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);

    //SOQL query that returns weight value at six weeks mark (Between 35 & 56; closer to 35) 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account account : [
            Select Id,Initial_Weight__c,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    WHERE Weight__c != NULL AND Status__c NOT IN ('Canceled', 'Cancelled') AND Days_since_first_appointment__c > 37 AND Days_since_first_appointment__c < 55  
                    Order by Scheduled_time__c asc
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Assigning account's inital weight value to variable
            Decimal InitialWeight = NULL;    
            
            //Declare a decimal variable to store latest weight value 
            Decimal SixWeeksWeight = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                SixWeeksWeight = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }
            
            if (account.Initial_Weight__c != NULL) {
                InitialWeight = account.initial_weight__c;
            }
                
            Decimal WeightLostAtSixWeeks = InitialWeight - SixWeeksWeight;
            Decimal PercentWeightLoss = (WeightLostAtSixWeeks/InitialWeight)*100; 
            
            //if (SixWeeksWeight == NULL) {SixWeeksWeight = 0;
            //   } else {
            
            AccountsToUpdate.add(new Account(
                Id = account.Id,
                Percent_weight_loss_at_6_weeks__c = PercentWeightLoss
            ));
                    
            //}
                         
        }   
        
        update AccountsToUpdate;
        
        }
      }
Here is some background information on what I'm trying to do with this code:

I have two objects; Patients (persons accounts, Master object) and Appointments (Detail object) and I'm trying to build a trigger (With SOQL query) that returns percent weight loss at 6 weeks mark per account on a custom field (Percent_weight_loss_at_6_weeks__c) that is built on the account (Persons account) object:
 
Object #1: (Appointments)
 
Appointment ID  Account ID,   Account Name,  Apt Date,   Weight....etc.
-----------------------------------------------------------------------------------------------
Apts_001112       001                John                 01/01/2017     160
Apts_001114       002                Nicole               11/05/2016      180
Apts_001113       001                John                 04/05/2017     175
Apts_001115       003                Mark                 05/05/2017      190   
Apts_001116       002                Nicole               12/15/2016      200
...
...
...
 
Object #2: (Accounts)
 
 ID,      Name         Percent Weight Loss at 6 weeks. (This the metric that I'm trying to return in the account object) 
----------------------------------------------------------------------------------------------
 001     John          3%
 002     Nicole        2%
 003     Mark          3%     
----------------------------------------------------------------------------------------------
P.S:

The trigger worked for patients (Person accounts) who have existing appointments at 6 weeks mark (between 35 - 56) but didn't work; threw the above error message ^, for patients who don't have appointment at 6 weeks mark.
Hello,

I'm new to Apex and I'm trying to write this trigger that evaluates multiple conditions on the Accounts object (through if statements). If the conditions are met then the trigger creates a task related to the Account. 

Here is the code for the trigger:
 
//This Trigger get fired daily at 7 Am in the morning. It checks for patients who are due for BIA exams and set tasks to assistant to get a BIA exam for patient who are due
Trigger AddTaskForVitalsCheck on Account(before update,after update) {

//Variable that returns a date; 28 days from today.
Date DateMonthAgo = date.today().addDays(-28); 
    
//Create a task list that includes all the tasks
    List <Task> TaskList = new List<Task>();
    
    Set<Id> AccIds=new set<Id>();
    for(Account a:trigger.new)
    {
    AccIds.add(a.Id);
    }
  
//Create a tasklist that includes all the tasks that are created today
   List<Task> TodaysTask =new List<Task>([SELECT Id,whatId from Task Where whatId in :AccIds AND CreatedDate=TODAY AND subject like '%vitals%' ]);
    
//Get the related Task for the accounts in this trigger
//Map <Id,Account> AcctsWithTask = new Map <Id,Account>([SELECT Id,(SELECT Id FROM Tasks) FROM Account WHERE Id IN :AccIds]);
    
// Add an Task for each account if account meets crietria and it doesn't already have a task.
// Iterate through each account.
    for(Account a : Trigger.New) {
    
        if (a.Next_appointment_date__c == date.today() && a.Latest_BIA_date__c < DateMonthAgo&&TodaysTask.size() < 1) {
            //If it doesn't, add a task
            TaskList.add(new Task(Subject= 'Nicole: Patient is due their monthly vitals check',
                                  Description= 'Nicole, It has been more than a month since vitals were taken for this patient. Please get patient\'s waist circumference, hip circumference, blood pressure and BIA exam prior to the appointment.',
                                  ActivityDate= Date.today().addDays(1),
                                  WhatID = a.Id));
        }           
    }
    
        insert TaskList;
        
        }

Here is the code for test class:​
 
@isTest(SeeAllData=true)
Private class VitalsAndLabsAutomation_TestClass {

    @isTest static void InsertAppointmentsAndLabs() {

        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        
        //Get the recordtype ID associated with the patients record type
        RecordType rt = [SELECT ID,Name FROM RecordType WHERE SobjectType='Account' and Name='Patients' Limit 1];
        
        accnts.name = 'Fares';
        accnts.RecordTypeID = rt.id;
        accnts.Next_Appointment__c = date.today();
        
        insert accnts;
        
        //I cant edit accnts.Latest_BIA_date__c field since its a roll-up field, so instead I added an appointment record that should autofill accnts.Latest_BIA_date__c with a date that is less than 30 days from today 
        appt.weight__c = 200;
        appt.scheduled_time__c = date.today().AddDays(-30);
        appt.patient__c = accnts.id;
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        insert appt;
        update accnts;
       
        lb.value__c = 100;
        lb.Specimen_Received__c = date.today().AddDays(-90);
        lb.patient__c = accnts.id;
        lb.Observation_Description__c = 'Trigl';
                
        insert lb;

        }
        
         //Update existing patient's appointment 
        @isTest static void updateAppointmentsAndLabs() {
        
        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Appointments__c SecondAppt = new appointments__c();
        Labs__c lb = new labs__c();
        
        accnts.ID = '00161000013cLIg';
        accnts.Next_Appointment__c = date.today();
        
        Update accnts;
        
        appt.weight__c = 320;
        appt.patient__c = '00161000013cLIg';
        appt.ID = 'a0A6100000USumJ';
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        Update appt;
        
        lb.id = 'a0E4B000002Bzdt';
                
        Update lb;
        
        }
}

Here is the configuration for Latest_BIA_date__c​ roll-up field:

User-added image
Hello,

I'm new to Apex and I'm trying to write this trigger that evaluates multiple conditions on the Accounts object (through if statements). If the conditions are met then the trigger creates a task related to the Account. 

Here is the code for the trigger:
 
//This Trigger get fired daily at 7 Am in the morning. It checks for patients who are due for BIA exams and set tasks to assistant to get a BIA exam for patient who are due
Trigger AddTaskForVitalsCheck on Account(before update,after update) {

//Variable that returns a date; 28 days from today.
Date DateMonthAgo = date.today().addDays(-28); 
    
//Create a task list that includes all the tasks
    List <Task> TaskList = new List<Task>();
    
    Set<Id> AccIds=new set<Id>();
    for(Account a:trigger.new)
    {
    AccIds.add(a.Id);
    }
  
//Create a tasklist that includes all the tasks that are created today
   List<Task> TodaysTask =new List<Task>([SELECT Id,whatId from Task Where whatId in :AccIds AND CreatedDate=TODAY AND subject like '%vitals%' ]);
    
//Get the related Task for the accounts in this trigger
//Map <Id,Account> AcctsWithTask = new Map <Id,Account>([SELECT Id,(SELECT Id FROM Tasks) FROM Account WHERE Id IN :AccIds]);
    
// Add an Task for each account if account meets crietria and it doesn't already have a task.
// Iterate through each account.
    for(Account a : Trigger.New) {
    
        if (a.Next_appointment_date__c == date.today() && a.Latest_BIA_date__c < DateMonthAgo&&TodaysTask.size() < 1) {
            //If it doesn't, add a task
            TaskList.add(new Task(Subject= 'Nicole: Patient is due their monthly vitals check',
                                  Description= 'Nicole, It has been more than a month since vitals were taken for this patient. Please get patient\'s waist circumference, hip circumference, blood pressure and BIA exam prior to the appointment.',
                                  ActivityDate= Date.today().addDays(1),
                                  WhatID = a.Id));
        }           
    }
    
        insert TaskList;
        
        }

Here is the code for test class:
 
@isTest(SeeAllData=true)
Private class VitalsAndLabsAutomation_TestClass {

    @isTest static void InsertAppointmentsAndLabs() {

        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        
        //Get the recordtype ID associated with the patients record type
        RecordType rt = [SELECT ID,Name FROM RecordType WHERE SobjectType='Account' and Name='Patients' Limit 1];
        
        accnts.name = 'Fares';
        accnts.RecordTypeID = rt.id;
        accnts.Next_Appointment__c = date.today();
        
        insert accnts;
        
        //I cant edit accnts.Latest_BIA_date__c field since its a roll-up field, so instead I added an appointment record that should autofill accnts.Latest_BIA_date__c with a date that is less than 30 days from today 
        appt.weight__c = 200;
        appt.scheduled_time__c = date.today().AddDays(-30);
        appt.patient__c = accnts.id;
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        insert appt;
        update accnts;
       
        lb.value__c = 100;
        lb.Specimen_Received__c = date.today().AddDays(-90);
        lb.patient__c = accnts.id;
        lb.Observation_Description__c = 'Trigl';
                
        insert lb;

        }
        
         //Update existing patient's appointment 
        @isTest static void updateAppointmentsAndLabs() {
        
        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Appointments__c SecondAppt = new appointments__c();
        Labs__c lb = new labs__c();
        
        accnts.ID = '00161000013cLIg';
        accnts.Next_Appointment__c = date.today();
        
        Update accnts;
        
        appt.weight__c = 320;
        appt.patient__c = '00161000013cLIg';
        appt.ID = 'a0A6100000USumJ';
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        Update appt;
        
        lb.id = 'a0E4B000002Bzdt';
                
        Update lb;
        
        }
}
Here is the configuration for Latest_BIA_date__c​ roll-up field:

User-added image

Thanks in advance,
M.




 
Hello,

I'm new to Apex and I'm trying to write this trigger that evaluates multiple conditions on the Accounts object (through if statements). If the conditions are met then the trigger creates a task related to the Account. 

Here is the code for the trigger:
 
//This Trigger get fired daily at 7 Am in the morning. It checks for patients who are due for BIAs and set tasks to Nicole so she can get a BIA exam for patient
Trigger AddTaskForVitalsCheck on Account(before update,after update) {

//Variable that returns a date; 28 days from today.
Date DateMonthAgo = date.today().addDays(-28); 
    
//Create a task list that includes all the tasks
    List <Task> TaskList = new List<Task>();
    
    Set<Id> AccIds=new set<Id>();
    for(Account a:trigger.new)
    {
    AccIds.add(a.Id);
    }
  
//Create a tasklist that includes all the tasks that are created today
   List<Task> TodaysTask =new List<Task>([SELECT Id,whatId from Task Where whatId in :AccIds AND CreatedDate=TODAY AND subject like '%vitals%' ]);
    
//Get the related Task for the accounts in this trigger
//Map <Id,Account> AcctsWithTask = new Map <Id,Account>([SELECT Id,(SELECT Id FROM Tasks) FROM Account WHERE Id IN :AccIds]);
    
// Add an Task for each account if account meets crietria and it doesn't already have a task.
// Iterate through each account.
    for(Account a : Trigger.New) {
    
        if (a.Next_appointment_date__c == date.today() && a.Latest_BIA_date__c < DateMonthAgo&&TodaysTask.size() < 1) {
            //If it doesn't, add a task
            TaskList.add(new Task(Subject= 'Nicole: Patient is due their monthly vitals check',
                                  Description= 'Nicole, It has been more than a month since vitals were taken for this patient. Please get patient\'s waist circumference, hip circumference, blood pressure and BIA exam prior to the appointment.',
                                  ActivityDate= Date.today().addDays(1),
                                  WhatID = a.Id));
        }           
    }
    
        insert TaskList;
        
        }

Here is the test class: 
 
@isTest(SeeAllData=true)
Private class VitalsAndLabsAutomation_TestClass {

    @isTest static void InsertAppointmentsAndLabs() {

Account accnts = new Account();
Appointments__c appt = new Appointments__c();
Appointments__c SecondAppt = new appointments__c();
Labs__c lb = new labs__c();

RecordType rt = [SELECT ID,Name FROM RecordType WHERE SobjectType='Account' and Name='Patients' Limit 1];
        
        accnts.name = 'Fares';
        accnts.RecordTypeID = rt.id;
        accnts.Next_Appointment__c = date.today();
        
        insert accnts;
        
        appt.weight__c = 200;
        appt.scheduled_time__c = date.today().AddDays(-30);
        appt.patient__c = accnts.id;
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        insert appt;
       
        lb.value__c = 100;
        lb.Specimen_Received__c = date.today().AddDays(-90);
        lb.patient__c = accnts.id;
        lb.Observation_Description__c = 'Trigl';
        
        
        insert lb;
        
        SecondAppt.scheduled_time__c = date.today();
        SecondAppt.patient__c = accnts.id;
        
        insert SecondAppt;
        
        }
        
         //Update existing patient's appointment 
         @isTest static void updateAppointmentsAndLabs() {
        
Account accnts = new Account();
Appointments__c appt = new Appointments__c();
Appointments__c SecondAppt = new appointments__c();
Labs__c lb = new labs__c();
        
        accnts.ID = '00161000013cLIg';
        accnts.Next_Appointment__c = date.today();
        
        Update accnts;
        
        appt.weight__c = 320;
        appt.patient__c = '00161000013cLIg';
        appt.ID = 'a0A6100000USumJ';
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        Update appt;
        
        Secondappt.weight__c = 300;
        Secondappt.scheduled_time__c = date.today();
        Secondappt.patient__c = '00161000013cLIg';
        Secondappt.ID = 'a0A6100000JkgIj';       
        
        Update secondappt;
        
        }
}

 
The code coverage for the Trigger below is only 56%, trying to get it to atleast a 75%
 
Trigger GetInitialWeightValue on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);
    
//SOQL query that returns that initial weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>(); 
        for (Account account : [
            Select Id,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    WHERE Weight__c != NULL AND Status__c NOT IN ('Canceled', 'Cancelled')
                    Order by Scheduled_time__c ASC
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store initial weight value 
            Decimal IW = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                IW = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_Weight__c = IW
            ));
            
        }   
        
        update accountsToUpdate;
        
        }
      }

Here is the testing class that I used:
 
@isTest
Private class InsertWeightToAppointment {

    @isTest static void InsertAppointment() {
        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        
        appt.weight__c = 200;
        appt.scheduled_time__c = date.today();
        appt.patient__c = '00161000013cLIg';
        appt.status__c = 'Completed';
        
        insert appt;
        
        lb.value__c = 100;
        lb.Specimen_Received__c = date.today();
        lb.patient__c = '00161000013cLIg';
        lb.Observation_Description__c = 'LDL';
        
        insert lb;
               
        
        }
        
    @isTest static void UpdateAppointment() {
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        appt.id = 'a0A6100000UUBeK';
        appt.weight__c = 100;
        appt.scheduled_time__c = date.today();
        appt.patient__c = '00161000013bPD9';
        
        update appt;   
        
        lb.value__c = 180;
        lb.Specimen_Received__c = date.today()-30;
        lb.patient__c = '00161000013cLIg';
        lb.Observation_Description__c = 'LDL';
        lb.id = 'a0E61000005Pg21';
        
        update lb;
        
        }
     
}
Why am I getting this error?

Problem:

I'm trying to get the first occurrences value for each of the labs records on Salesforce from the Labs object and return it on the labs values custom fields (inital a1c value, inital LDL value..etc.) on the Accounts records level.

P.S: 

Accounts and Labs have a parent-child relationship with accounts being the parents records and labs being the child records. 

Code:
 
/* Get the first occurrence value for each of the labs from the Labs object and return it on the labs value fields on Accounts record leve. */
Trigger GetInitialLabsValue on labs__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

for (labs__c lb : trigger.new) {
        accountIds.add(lb.Patient__c);
    }

//Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);
    
//SOQL query that returns that initial weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>(); 
        for (Account account : [
            SELECT Id,
                (
                    SELECT Specimen_Received__c, Value__c
                    From labs__r
                    WHERE Value__c != NULL
                    Order by Specimen_Received__c ASC
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store initial labs value for each of the labs 
            Decimal IA1C = NULL;
            Decimal ILDL = NULL;
            Decimal IHDL = Null;
            Decimal ITrigl = NULL;
            
            // Get(0) to return the first element in the list value for each of the labs
            if (!account.Labs__r.isEmpty() && account.Labs__r.Observation_Description__c.contains('A1C') ) {
                IA1C = account.labs__r.get(0).Value__c;
            } Else if (account.Labs__r.isEmpty() && account.Labs__r.Observation_Description__c.contains('LDL')){
                 ILDL = account.labs__r.get(0).Value__c;
            } Else if (account.Labs__r.isEmpty() && account.Labs__r.Observation_Description__c.contains('HDL')){
                 IHDL = account.labs__r.get(0).Value__c;
            } Else if (account.Labs__r.isEmpty() && account.Labs__r.Observation_Description__c.contains('Trigl')){
                 ITrigl = account.labs__r.get(0).Value__c;}

accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_A1c_labs_value__c = IA1C,
                initial_LDL_labs_value__c = ILDL,
                initial_HDL_labs_value__c = IHDL,
                initial_Trigl_labs_value__c = ITrigl
            ));
            
        }   
        
        Update accountsToUpdate;
        
        }
      }

 
Context:

I'm new to Apex and SOQL. I have two objects; Accounts (Master object) and Appointments (Child object) and I'm trying to write a trigger (With SOQL query) that returns the inital weight value (corresponding to the inital date) per account and another trigger that return the latest weight value (corresponding to the most recent appointment) per account on the custom fields inital_weight__c and latest_weight__c respectively. Both fields are built on the account (Persons account) object:

Problem:

While the trigger for the latest weight (GetLatestWeightValue) works like a charm, the other trigger for the initial weight value (GetInitialWeightValue)​ is not working for some reason.

I attached both trigger's codes below, I'd really appreciate it if someone can take a look at the codes and point out what wrong with the 1st trigger; GetInitialWeightValue

GetInitialWeightValue Trigger:  returns the inital weight value (corresponding to the inital date) per account
Trigger GetInitialWeightValue on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);
    
//SOQL query that returns that initial weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>(); 
        for (Account account : [
            Select Id,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    Order by Scheduled_time__c ASC
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store initial weight value 
            Decimal IW = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                IW = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_Weight__c = IW
            ));
            
        }   
        
        update accountsToUpdate;
        
        }
      }
GetLatestWeightValue​ Trigger:  returns the latest weight value (corresponding to the inital date) per account
Trigger GetLatestWeightValue on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);

    //SOQL query that returns that latest weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account account : [
            Select Id,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    Order by Scheduled_time__c desc
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store latest weight value 
            Decimal LW = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                LW = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                Latest_weight__c = LW
            ));
                         
        }   
        
        update accountsToUpdate;
        
        }
      }
Error message: 

Compile Error: Method does not exist or incorrect signature: account.Dr_Chrono_appointments__r.get(Integer) at line 58 column 22​

Problem:

I'm new to Apex and SOQL. I have two objects; Accounts (Master object) and Appointments (Child object) and I'm trying to write a trigger (With SOQL query) that returns the inital weight value (corresponding to the inital date) and latest weight (corresponding  to the most recent appointment) per account on custom fields inital_weight__c and latest_weight__c respectively. Both fields are built on the account (Persons account) object:

Code:
Trigger GetLatestAndInitalWeightValue on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);

    //SOQL query that returns that latest weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account account : [
            Select Id,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    Order by Scheduled_time__c desc
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store latest weight value 
            Decimal LW = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                LW = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                Latest_weight__c = LW
            ));
            }
              //SOQL query that returns that inital weight value 
             
        for (Account account2 : [
            Select Id,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    Order by Scheduled_time__c ASC
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store inital weight value 
            Decimal IW = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                IW = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                Inital_Weight__c = IW
            ));
                         
        }   
        
        update accountsToUpdate;
        
        }
      }

 
Overview/context:

I have a new phone system that sync calls summary into Salesforce in a form of tasks. Now I'm developing a trigger that fires each time these tasks (Call summary) are logged with a certain critieria, creating a new tasks on Salesforce based on the call result.

Code:
Trigger AssignTasksBasedOnPhoneTags on Task (After insert) {

    // Create a list that includes all the Tasks
    List<Task> TasksList = new List<Task>();
    
    Task NewestSalesRelatedTask = new Task();
    
    NewestSalesRelatedTask = [SELECT Id, whatid, CallDisposition, whoid
                                 FROM Task 
                                 WHERE CallDisposition LIKE '%Sales inquiries%' AND CallDisposition LIKE '%Call requires a follow-up%'
                                 ORDER BY ActivityDate ASC
                                 LIMIT 1];
                                                        
                                                                            
    if(NewestSalesRelatedTask.CallDisposition.contains('Sales inquiries') && NewestSalesRelatedTask.CallDisposition.contains('Call requires a follow-up')) {
    
    TasksList.add(new Task(subject= 'Alissa: A new lead needs follow up',
                 Description= 'Hey Alissa, based on this lead last call, this need lead need to be followed up with. Please refer to leads previous call',
                 ActivityDate= Date.today().addDays(1),
                 WhatID= NewestSalesRelatedTask.whatid));
    } 
    insert TasksList;
}

Reproduction/Error message:
 
Create any new task manually or the telephony system would lead to this error message. Even when conditition is not met: (CallDisposition LIKE '%Sales inquiries%' AND CallDisposition LIKE '%Call requires a follow-up%')

" Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger AssignTasksBasedOnPhoneTags caused an unexpected exception, contact your administrator: AssignTasksBasedOnPhoneTags: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AssignTasksBasedOnPhoneTags: maximum trigger depth exceeded Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert Task trigger event AfterInsert: []: () "
I'm trying to write a test class and load bunch of test lead's data but for some reason when I call the static resource (that has my CSV) is not recognizing the custom fields. Example, Lead_insurance_Id__c

My CSV file - static resource:
// Example of how my CSV looks like

Id, Firstname, Lastname, Leads_Insurance_ID__c,..etc

000012, Fares, Alsyoufi, 12184111, ..etc
000011, Fare,syoufi, 12184211, ..etc
000013, Fares, syouf, 12184311, ..etc

My test class:
 
@isTest 
global class DataUtil {
    static testmethod void testLoadData() {
        // Load the test accounts from the static resource
        List<sObject> ls = Test.loadData(Account.sObjectType, 'TestData');
        
       }
}

Error message: 

User-added image

Seems like the standard Salesforce fields didn't cause any execptions but custom fields did (I tried other one beside Lead_Insurance_Id__c) and I still got the same error message. 

P.S:
I've tried to change my CSV header to all of these formats but non helped:

LEADS_INSURANCE_ID__c
Leads_insurance_Id__c
Lead.DLeads_insurance_Id__c
Insurance ID (Field's label)
Hi,

I have deployed this Apex Testing class in production that messed up my whole production org; it got to a point where I'm not able to deploy anything on production nor able to delete it (the Apex class that's causing the issue). 

Here what I did to delete test class:

1. I download Eclipse and insalled the Foce.com IDE.
2. Then I created Foce.com two projects; one includes all my master production org components and one includes all of my sandbox components.
3. After that I went to sandbox project and altered my class file.xml to "Deleted" and changed four of my triggers (tied to the class, not needed anymore) to "Inactive"
4. I attempted to deploy the five components (referenced above) to production in order to delete trigger and deactive class but I failed. Got this error message and coverage results:
 
*** Deployment Log ***
Result: FAILED
Date: October 17, 2017 5:35:32 PM PDT

# Deployed From:
   Project name: Inbody_replacing
   Username: mahmoud@enarahealth.com.sandbox
   Endpoint: test.salesforce.com

# Deployed To:
   Username: mahmoud@enarahealth.com
   Endpoint: login.salesforce.com

# Deploy Results:
   File Name:    classes/InsertInbodyData_TestClass.cls
   Full Name:  InsertInbodyData_TestClass
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

   File Name:    package.xml
   Full Name:  package.xml
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetInitialPBFValue.trigger
   Full Name:  GetInitialPBFValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetInitialSMMValue.trigger
   Full Name:  GetInitialSMMValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetLatestPBFValue.trigger
   Full Name:  GetLatestPBFValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetLatestSMMValue.trigger
   Full Name:  GetLatestSMMValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

# Test Results:

Run Failures:
  InsertInbodyData_TestClass.UpdateBIA System.DmlException: Update failed. First exception on row 0 with id a076100000HLRd3AAH; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
User-added image

Here is the code for Apex class (InsertInbodyData_TestClass) and one of the triggers (GetInitialPBFValue) (The triggers logic is identical across all four triggers).
 
Trigger GetInitialPBFValue on Inbody__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Inbody__c inbdy : trigger.new) {
        accountIds.add(inbdy.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);

    //SOQL query that returns that latest weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account account : [
            Select Id,
                (
                    SELECT Test_Date_Time__c, Percent_Body_Fat__c
                    FROM Inbody__r
                    WHERE Percent_Body_Fat__c != NULL
                    ORDER by Test_Date_Time__c asc
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store latest weight value 
            Decimal IPBF = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Inbody__r.isEmpty()) {
                IPBF = account.Inbody__r.get(0).Percent_Body_Fat__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_PBF_Value__c = IPBF
               
            ));
                         
        }   
        
        Update accountsToUpdate;
        
        }
      }
GetInitialPBFValue Trigger:
@isTest(SeeAllData=true)
Private class InsertInbodyData_TestClass {

    @isTest static void InsertInbody() {
        Account accnts = new Account();
        Inbody__c BIA = new Inbody__c();
        
        RecordType rt = [SELECT ID,Name FROM RecordType WHERE SobjectType='Account' and Name='Patients' Limit 1];
        
        accnts.name = 'afagas';
        accnts.RecordTypeID = rt.id;
        
        insert accnts;
        
        BIA.Skeletal_Muscle_Mass__c = 200;
        BIA.Percent_Body_Fat__c = 160;
        BIA.Test_Date_Time__c = Date.today();
        BIA.patient__c = accnts.id;
        
        insert BIA;
               
        }
        
    @isTest static void UpdateBIA() {
        Inbody__c BIA = new Inbody__c();
        BIA.id = 'a076100000HLRd3';
        BIA.weight__c = 100;
        BIA.Test_Date_Time__c = date.today();
        BIA.patient__c = '0016100000V5qTw';
        
        update BIA;   
        
        }
     
}
This issue had became a HUGE bottleneck in my development process, any input would be greatly appreciated!





 
Hi,

I have deployed this Apex Testing class in production that messed up my whole production org; it got to a point where I'm not able to deploy anything on production nor able to delete it (the Apex class that's causing the issue). 

Here what I did to delete test class:

1. I download Eclipse and insalled the Foce.com IDE.
2. Then I created Foce.com two projects; one includes all my master production org components and one includes all of my sandbox components.
3. After that I went to sandbox project and altered my class file.xml to "Deleted" and changed four of my triggers (tied to the class, not needed anymore) to "Inactive"
4. I attempted to deploy the five components (referenced above) to production in order to delete trigger and deactive class but I failed. Got this error message and coverage results:
*** Deployment Log ***
Result: FAILED
Date: October 17, 2017 5:35:32 PM PDT

# Deployed From:
   Project name: Inbody_replacing
   Username: mahmoud@enarahealth.com.sandbox
   Endpoint: test.salesforce.com

# Deployed To:
   Username: mahmoud@enarahealth.com
   Endpoint: login.salesforce.com

# Deploy Results:
   File Name:    classes/InsertInbodyData_TestClass.cls
   Full Name:  InsertInbodyData_TestClass
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

   File Name:    package.xml
   Full Name:  package.xml
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetInitialPBFValue.trigger
   Full Name:  GetInitialPBFValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetInitialSMMValue.trigger
   Full Name:  GetInitialSMMValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetLatestPBFValue.trigger
   Full Name:  GetLatestPBFValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/GetLatestSMMValue.trigger
   Full Name:  GetLatestSMMValue
   Action:  NO ACTION
   Result:  SUCCESS
   Problem: n/a

# Test Results:

Run Failures:
  InsertInbodyData_TestClass.UpdateBIA System.DmlException: Update failed. First exception on row 0 with id a076100000HLRd3AAH; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
Deployement coverage results:

User-added image

Here is the code for Apex class (InsertInbodyData_TestClass) and one of the triggers (GetInitialPBFValue) (The triggers logic is identical across all four triggers).
 
Trigger GetInitialPBFValue on Inbody__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Inbody__c inbdy : trigger.new) {
        accountIds.add(inbdy.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);

    //SOQL query that returns that latest weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account account : [
            Select Id,
                (
                    SELECT Test_Date_Time__c, Percent_Body_Fat__c
                    FROM Inbody__r
                    WHERE Percent_Body_Fat__c != NULL
                    ORDER by Test_Date_Time__c asc
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store latest weight value 
            Decimal IPBF = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Inbody__r.isEmpty()) {
                IPBF = account.Inbody__r.get(0).Percent_Body_Fat__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_PBF_Value__c = IPBF
               
            ));
                         
        }   
        
        Update accountsToUpdate;
        
        }
      }

GetInitialPBFValue Trigger:
 
@isTest(SeeAllData=true)
Private class InsertInbodyData_TestClass {

    @isTest static void InsertInbody() {
        Account accnts = new Account();
        Inbody__c BIA = new Inbody__c();
        
        RecordType rt = [SELECT ID,Name FROM RecordType WHERE SobjectType='Account' and Name='Patients' Limit 1];
        
        accnts.name = 'afagas';
        accnts.RecordTypeID = rt.id;
        
        insert accnts;
        
        BIA.Skeletal_Muscle_Mass__c = 200;
        BIA.Percent_Body_Fat__c = 160;
        BIA.Test_Date_Time__c = Date.today();
        BIA.patient__c = accnts.id;
        
        insert BIA;
               
        }
        
    @isTest static void UpdateBIA() {
        Inbody__c BIA = new Inbody__c();
        BIA.id = 'a076100000HLRd3';
        BIA.weight__c = 100;
        BIA.Test_Date_Time__c = date.today();
        BIA.patient__c = '0016100000V5qTw';
        
        update BIA;   
        
        }
     
}
This issue had became a HUGE bottleneck in my development process, any input would be greatly appreciated!
 
Hello,

I'm new to Salesforce Apex. I keep getting this error message when I try save my code eventhough I've declared the variable already..

User-added image

Compile Error: Variable does not exist: BTLog at line 16 column 33    ​
Trigger AutocreateBTWeightRecordsAndMatchitToAccount on bodytrace__c (after insert) {
    for (BodyTrace__c BTLog : Trigger.new) {
    
    Bodytrace_weight__c BTWeight = new Bodytrace_Weight__c();
 
    BTWeight.IMEI__c             =  BTLog.IMEI__c;
    BTWeight.Weight__c           =  BTLog.Values_weight__c;
    BTWeight.Date_of_reading__c  =  BTLog.CreatedDate;
    BTWeight.bodytrace_log__c    =  BTLog.ID;
         
    Insert BTWeight;
      
    }
    
        For (Account Accnt : Trigger.new) {
            if(accnt.IMEI__c == BTLog.IMEI__c){
            BTWeight.Account__c = account.ID;
            }
        }
}
Background on what I'm trying to do:

I'm trying to build a trigger that create a weight reading records (Bodytrace_Weight__c) based of weight logs records (Bodytrace_Weight__c). After that I'd like to auto-assign (Bodytrace_Weight__c) to the patient who got weighted based on the serial number that is found on both; account object and Bodytrace_Weight__c object.

Please let me know what's the best way to build this. Thanks!
Hello,

High-level problem:

I'm trying to build a caculated filed that returns percent weight loss for patient accounts at 6 weeks mark. I did that through building a trigger and custom filed on the account object. Trigger works for some accounts and throw this error message (below) for other accounts.  

Error mesage return upon saving records:

I keep getting this error message upon saving editing/inserting new appointments (Child/Detail records) for persons account. 

Review all error messages below to correct your data.
Apex trigger ReturnPercentWeightLossAt6WeeksMark caused an unexpected exception, contact your administrator: ReturnPercentWeightLossAt6WeeksMark: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.ReturnPercentWeightLossAt6WeeksMark: line 42, column 1

(Please refer to the end of the page if you want a get a clearer idea of what I'm trying to accomplish by building this trigger)
 
Trigger ReturnPercentWeightLossAt6WeeksMark on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);

    //SOQL query that returns weight value at six weeks mark (Between 35 & 56; closer to 35) 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account account : [
            Select Id,Initial_Weight__c,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    WHERE Weight__c != NULL AND Status__c NOT IN ('Canceled', 'Cancelled') AND Days_since_first_appointment__c > 37 AND Days_since_first_appointment__c < 55  
                    Order by Scheduled_time__c asc
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Assigning account's inital weight value to variable
            Decimal InitialWeight = NULL;    
            
            //Declare a decimal variable to store latest weight value 
            Decimal SixWeeksWeight = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                SixWeeksWeight = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }
            
            if (account.Initial_Weight__c != NULL) {
                InitialWeight = account.initial_weight__c;
            }
                
            Decimal WeightLostAtSixWeeks = InitialWeight - SixWeeksWeight;
            Decimal PercentWeightLoss = (WeightLostAtSixWeeks/InitialWeight)*100; 
            
            //if (SixWeeksWeight == NULL) {SixWeeksWeight = 0;
            //   } else {
            
            AccountsToUpdate.add(new Account(
                Id = account.Id,
                Percent_weight_loss_at_6_weeks__c = PercentWeightLoss
            ));
                    
            //}
                         
        }   
        
        update AccountsToUpdate;
        
        }
      }
Here is some background information on what I'm trying to do with this code:

I have two objects; Patients (persons accounts, Master object) and Appointments (Detail object) and I'm trying to build a trigger (With SOQL query) that returns percent weight loss at 6 weeks mark per account on a custom field (Percent_weight_loss_at_6_weeks__c) that is built on the account (Persons account) object:
 
Object #1: (Appointments)
 
Appointment ID  Account ID,   Account Name,  Apt Date,   Weight....etc.
-----------------------------------------------------------------------------------------------
Apts_001112       001                John                 01/01/2017     160
Apts_001114       002                Nicole               11/05/2016      180
Apts_001113       001                John                 04/05/2017     175
Apts_001115       003                Mark                 05/05/2017      190   
Apts_001116       002                Nicole               12/15/2016      200
...
...
...
 
Object #2: (Accounts)
 
 ID,      Name         Percent Weight Loss at 6 weeks. (This the metric that I'm trying to return in the account object) 
----------------------------------------------------------------------------------------------
 001     John          3%
 002     Nicole        2%
 003     Mark          3%     
----------------------------------------------------------------------------------------------
P.S:

The trigger worked for patients (Person accounts) who have existing appointments at 6 weeks mark (between 35 - 56) but didn't work; threw the above error message ^, for patients who don't have appointment at 6 weeks mark.
Hello,

I'm new to Apex and I'm trying to write this trigger that evaluates multiple conditions on the Accounts object (through if statements). If the conditions are met then the trigger creates a task related to the Account. 

Here is the code for the trigger:
 
//This Trigger get fired daily at 7 Am in the morning. It checks for patients who are due for BIA exams and set tasks to assistant to get a BIA exam for patient who are due
Trigger AddTaskForVitalsCheck on Account(before update,after update) {

//Variable that returns a date; 28 days from today.
Date DateMonthAgo = date.today().addDays(-28); 
    
//Create a task list that includes all the tasks
    List <Task> TaskList = new List<Task>();
    
    Set<Id> AccIds=new set<Id>();
    for(Account a:trigger.new)
    {
    AccIds.add(a.Id);
    }
  
//Create a tasklist that includes all the tasks that are created today
   List<Task> TodaysTask =new List<Task>([SELECT Id,whatId from Task Where whatId in :AccIds AND CreatedDate=TODAY AND subject like '%vitals%' ]);
    
//Get the related Task for the accounts in this trigger
//Map <Id,Account> AcctsWithTask = new Map <Id,Account>([SELECT Id,(SELECT Id FROM Tasks) FROM Account WHERE Id IN :AccIds]);
    
// Add an Task for each account if account meets crietria and it doesn't already have a task.
// Iterate through each account.
    for(Account a : Trigger.New) {
    
        if (a.Next_appointment_date__c == date.today() && a.Latest_BIA_date__c < DateMonthAgo&&TodaysTask.size() < 1) {
            //If it doesn't, add a task
            TaskList.add(new Task(Subject= 'Nicole: Patient is due their monthly vitals check',
                                  Description= 'Nicole, It has been more than a month since vitals were taken for this patient. Please get patient\'s waist circumference, hip circumference, blood pressure and BIA exam prior to the appointment.',
                                  ActivityDate= Date.today().addDays(1),
                                  WhatID = a.Id));
        }           
    }
    
        insert TaskList;
        
        }

Here is the code for test class:
 
@isTest(SeeAllData=true)
Private class VitalsAndLabsAutomation_TestClass {

    @isTest static void InsertAppointmentsAndLabs() {

        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        
        //Get the recordtype ID associated with the patients record type
        RecordType rt = [SELECT ID,Name FROM RecordType WHERE SobjectType='Account' and Name='Patients' Limit 1];
        
        accnts.name = 'Fares';
        accnts.RecordTypeID = rt.id;
        accnts.Next_Appointment__c = date.today();
        
        insert accnts;
        
        //I cant edit accnts.Latest_BIA_date__c field since its a roll-up field, so instead I added an appointment record that should autofill accnts.Latest_BIA_date__c with a date that is less than 30 days from today 
        appt.weight__c = 200;
        appt.scheduled_time__c = date.today().AddDays(-30);
        appt.patient__c = accnts.id;
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        insert appt;
        update accnts;
       
        lb.value__c = 100;
        lb.Specimen_Received__c = date.today().AddDays(-90);
        lb.patient__c = accnts.id;
        lb.Observation_Description__c = 'Trigl';
                
        insert lb;

        }
        
         //Update existing patient's appointment 
        @isTest static void updateAppointmentsAndLabs() {
        
        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Appointments__c SecondAppt = new appointments__c();
        Labs__c lb = new labs__c();
        
        accnts.ID = '00161000013cLIg';
        accnts.Next_Appointment__c = date.today();
        
        Update accnts;
        
        appt.weight__c = 320;
        appt.patient__c = '00161000013cLIg';
        appt.ID = 'a0A6100000USumJ';
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        Update appt;
        
        lb.id = 'a0E4B000002Bzdt';
                
        Update lb;
        
        }
}
Here is the configuration for Latest_BIA_date__c​ roll-up field:

User-added image

Thanks in advance,
M.




 
Hello,

I'm new to Apex and I'm trying to write this trigger that evaluates multiple conditions on the Accounts object (through if statements). If the conditions are met then the trigger creates a task related to the Account. 

Here is the code for the trigger:
 
//This Trigger get fired daily at 7 Am in the morning. It checks for patients who are due for BIAs and set tasks to Nicole so she can get a BIA exam for patient
Trigger AddTaskForVitalsCheck on Account(before update,after update) {

//Variable that returns a date; 28 days from today.
Date DateMonthAgo = date.today().addDays(-28); 
    
//Create a task list that includes all the tasks
    List <Task> TaskList = new List<Task>();
    
    Set<Id> AccIds=new set<Id>();
    for(Account a:trigger.new)
    {
    AccIds.add(a.Id);
    }
  
//Create a tasklist that includes all the tasks that are created today
   List<Task> TodaysTask =new List<Task>([SELECT Id,whatId from Task Where whatId in :AccIds AND CreatedDate=TODAY AND subject like '%vitals%' ]);
    
//Get the related Task for the accounts in this trigger
//Map <Id,Account> AcctsWithTask = new Map <Id,Account>([SELECT Id,(SELECT Id FROM Tasks) FROM Account WHERE Id IN :AccIds]);
    
// Add an Task for each account if account meets crietria and it doesn't already have a task.
// Iterate through each account.
    for(Account a : Trigger.New) {
    
        if (a.Next_appointment_date__c == date.today() && a.Latest_BIA_date__c < DateMonthAgo&&TodaysTask.size() < 1) {
            //If it doesn't, add a task
            TaskList.add(new Task(Subject= 'Nicole: Patient is due their monthly vitals check',
                                  Description= 'Nicole, It has been more than a month since vitals were taken for this patient. Please get patient\'s waist circumference, hip circumference, blood pressure and BIA exam prior to the appointment.',
                                  ActivityDate= Date.today().addDays(1),
                                  WhatID = a.Id));
        }           
    }
    
        insert TaskList;
        
        }

Here is the test class: 
 
@isTest(SeeAllData=true)
Private class VitalsAndLabsAutomation_TestClass {

    @isTest static void InsertAppointmentsAndLabs() {

Account accnts = new Account();
Appointments__c appt = new Appointments__c();
Appointments__c SecondAppt = new appointments__c();
Labs__c lb = new labs__c();

RecordType rt = [SELECT ID,Name FROM RecordType WHERE SobjectType='Account' and Name='Patients' Limit 1];
        
        accnts.name = 'Fares';
        accnts.RecordTypeID = rt.id;
        accnts.Next_Appointment__c = date.today();
        
        insert accnts;
        
        appt.weight__c = 200;
        appt.scheduled_time__c = date.today().AddDays(-30);
        appt.patient__c = accnts.id;
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        insert appt;
       
        lb.value__c = 100;
        lb.Specimen_Received__c = date.today().AddDays(-90);
        lb.patient__c = accnts.id;
        lb.Observation_Description__c = 'Trigl';
        
        
        insert lb;
        
        SecondAppt.scheduled_time__c = date.today();
        SecondAppt.patient__c = accnts.id;
        
        insert SecondAppt;
        
        }
        
         //Update existing patient's appointment 
         @isTest static void updateAppointmentsAndLabs() {
        
Account accnts = new Account();
Appointments__c appt = new Appointments__c();
Appointments__c SecondAppt = new appointments__c();
Labs__c lb = new labs__c();
        
        accnts.ID = '00161000013cLIg';
        accnts.Next_Appointment__c = date.today();
        
        Update accnts;
        
        appt.weight__c = 320;
        appt.patient__c = '00161000013cLIg';
        appt.ID = 'a0A6100000USumJ';
        appt.status__c = 'Completed';
        appt.Inbody_PBF__c = 300;
        appt.Inbody_SMM__c = 300;
        
        Update appt;
        
        Secondappt.weight__c = 300;
        Secondappt.scheduled_time__c = date.today();
        Secondappt.patient__c = '00161000013cLIg';
        Secondappt.ID = 'a0A6100000JkgIj';       
        
        Update secondappt;
        
        }
}

 
The code coverage for the Trigger below is only 56%, trying to get it to atleast a 75%
 
Trigger GetInitialWeightValue on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);
    
//SOQL query that returns that initial weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>(); 
        for (Account account : [
            Select Id,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    WHERE Weight__c != NULL AND Status__c NOT IN ('Canceled', 'Cancelled')
                    Order by Scheduled_time__c ASC
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store initial weight value 
            Decimal IW = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                IW = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_Weight__c = IW
            ));
            
        }   
        
        update accountsToUpdate;
        
        }
      }

Here is the testing class that I used:
 
@isTest
Private class InsertWeightToAppointment {

    @isTest static void InsertAppointment() {
        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        
        appt.weight__c = 200;
        appt.scheduled_time__c = date.today();
        appt.patient__c = '00161000013cLIg';
        appt.status__c = 'Completed';
        
        insert appt;
        
        lb.value__c = 100;
        lb.Specimen_Received__c = date.today();
        lb.patient__c = '00161000013cLIg';
        lb.Observation_Description__c = 'LDL';
        
        insert lb;
               
        
        }
        
    @isTest static void UpdateAppointment() {
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        appt.id = 'a0A6100000UUBeK';
        appt.weight__c = 100;
        appt.scheduled_time__c = date.today();
        appt.patient__c = '00161000013bPD9';
        
        update appt;   
        
        lb.value__c = 180;
        lb.Specimen_Received__c = date.today()-30;
        lb.patient__c = '00161000013cLIg';
        lb.Observation_Description__c = 'LDL';
        lb.id = 'a0E61000005Pg21';
        
        update lb;
        
        }
     
}
Hello,

I'm new to Apex and SOQl. I have two objects; Accounts (Master object) and Appointments (Child object) and I'm trying to write a trigger (With SOQL query) that returns the most recent appointment date (Max date) per account on a custom field (Most_Recent_Appointment_Date__c) that is built on the account (Persons account) object:
 
Object #1: (Appointments)
 
Appointment ID  Account ID,   Name,  Apt Date,   Weight....etc.
---------------------------------------------------------------------------------
Apts_001112       001                John      01/01/2017     160
Apts_001114       002                Nicole   11/05/2016      180
Apts_001113       001                John      04/05/2017     175
Apts_001115       003                Mark     05/05/2017      190   
Apts_001116       002                Nicole   12/15/2016      200
 
Object #2: (Accounts)
 
 ID,      Name....etc.
--------------------------
 001     John    
 002     Nicole   
 001     John     
 003     Mark      
 002     Nicole
-----------------------------------------------------------------------------------------------------------------------------------------------------
 
Trigger MostRecentAppointmentDate on Accounts (After update, after insert) {

List <Accounts> AccountsList = new List<Accounts>();

Set<id> AcntsID = new Set<id>();
    for(Account a:trigger.new) {
 AcntsID.add(a.ID);
}

For (Appointments Apts : Trigger.new) {
Appointments MostRecentApts = [SELECT Scheduled_date__c, Weight__c, Patient__c
                                            FROM Appointments__c
                                            WHERE Patients__c IN:AcntsID
                                            GROUP BY Patients__c
                                            ORDER BY Scheduled_date__c DESC
                                            LIMIT 1];

Set Most_Recent_Appointment_Date__c = MostRecentApts

}
Problem:

I created an Apex trigger that evaluates multiple conditions on the Accounts object (through if statements). If the conditions are met then the trigger creates a task related to the Accounts (the ones that meet the conditions). Now, since the trigger is from the (After Update type), tasks are being created everytime the account is updated (edited and saved). Which is creating tasks duplication 

Solution:

I tried to create a list of tasks that were created today() through a SOQL query then write an IF statement inside the trigger's loop that would exclude those accounts (that had tasks created today()) from the loop; don't create tasks for them..

However, after I added TodaysTasks list and the conditional statement (to avoid duplication) to the code, the tasks stopped getting assigned completely..(The highlighted code is the part that was added to avoid duplication)

User-added image
 
trigger AddTask on Account(after update) {
    // Variable that returns a date; 30 days from today.
    Date DateThirtyDaysAgo = date.today().addDays(-30); 
    
   // Create a task list that includes all the tasks
    List <Task> TaskList = new List<Task>();
    
   // Create a tasklist that includes all the tasks that are created today
    List<Task> TodaysTask = [SELECT accountid from Task Where Task_Created_Date__c = Today];
    
    // Get the related Task for the accounts in this trigger
    Map <Id,Account> AcctsWithTask = new Map <Id,Account>(
        [SELECT Id,(SELECT Id FROM Tasks) FROM Account WHERE Id IN :Trigger.New]);
    
    // Add an Task for each account if it doesn't already have one.
    // Iterate through each account.
    for(Account a : Trigger.New) {
        if (a.Next_appointment_date__c == date.today() && a.Latest_BIA_date__c < DateThirtyDaysAgo) {
            // If it doesn't, add a task
            TaskList.add(new Task(subject= 'This is a test',
                                  Description= 'This is a test',
                                  ActivityDate = Date.today().addDays(1),
                                  WhatID = a.Id));
        }           
    }
    
    if (TodaysTask.size() < 1) {
        insert TaskList;
        }











 
I'm trying to create a list of tasks that were created today() through a SOQL query so later I can write an if statement in the trigger that would exclude those account that were created today() from the loop.

User-added image