+ Start a Discussion
Adam NilaAdam Nila 

Apex Specialist - Automate Maintenance Requests

Ok, so I have a few questions about this specific challenge... First one of the requirements states:
"the Report Date field reflects the day the request was created, and the Due Date is calculated from the Report Date.".  Which request?  The original request or the new request?

Second, when checking the challenge I get the following notice:

"The challenge is expecting to find the closed Maintenance Request plus an 'New' Maintenance Request of type 'Routine Maintenance' with the same Vehicle as the closed one."

I have checked this trigger via the UI and it meets this requirement.  The new maintenance request does in fact show the same vehicle as the closed request, so why would I be getting this error?

 
for(Case C : triggerNew){
        	Case newCase = triggerNewMap.get(C.Id);
            Case oldCase = triggerOldMap.get(C.Id);
            if(newcase.status.contains('Closed') && !oldCase.status.contains('Closed') &&(newCase.recordTypeId=='012360000011FOeAAM' || newCase.recordTypeId =='012360000011FOjAAM')){
                for(Product2 prod : prodCodes){
                    
                    if(newCase.Product__c == prod.productCode){
                        prodExpiration = prod.lifespan_Months__c;
                    }
                }
                Decimal daysTilDue = prodExpiration * 30;
                Case maintenance = new Case(status='New',
                                            origin='Routine Maintenance',
                							//Added a routine maintenance type to the drop down field because I wasn't sure if it meant this 'type' or record type
                                            type='Routine Maintenance',
                                            //Id for 'Routine Maintenance' record type
                                            recordTypeId = '012360000011FOjAAM',
                                            reason= newCase.reason,
                                            subject='Routine Maintenance',
                                            product__c = newCase.Product__c,
                                           vehicle__c = newCase.Vehicle__c);
                maintenance.Date_Reported__c= newCase.CreatedDate.date();
                maintenance.Date_Due__c = maintenance.Date_Reported__c + daysTilDue.intValue();
                
                if(newCase.ContactId != null){
                    maintenance.ContactId = newCase.ContactId;
                }
                followUpCases.add(maintenance);
            }
        }//end of triggerNew for-loop
			insert followUpCases;

 
Best Answer chosen by Adam Nila
Jeff DouglasJeff Douglas
Great questions Adam! Sorry for the inconvenience.

The Report Date should be today and the Due Date should also be today (the Report Date) plus the number of days for the associated equipment's maintenance cycle.

You may also want to double check the requirements. I think it says to use the MaintenanceRequestHelper class instead of your trigger.

Jeff Douglas
Trailhead Developer Advocate

All Answers

Jeff DouglasJeff Douglas
Great questions Adam! Sorry for the inconvenience.

The Report Date should be today and the Due Date should also be today (the Report Date) plus the number of days for the associated equipment's maintenance cycle.

You may also want to double check the requirements. I think it says to use the MaintenanceRequestHelper class instead of your trigger.

Jeff Douglas
Trailhead Developer Advocate
This was selected as the best answer
Yogesh DYogesh D
'existing maintenance request of type Repair or Routine Maintenance is Closed' ... do we have to add these types in the Type picklist on Case to solve this problem. Are we allowed to do that ? Thank you.
ODagneaux99ODagneaux99
Hi,

I have this problem 

Challenge Not yet complete... here's what's wrong: 
Inserting a new Maintenance Request of type 'Routine Maintenance' and then closing it did not create of a new Maintenance Request based upon the original record correctly. The challenge is expecting to find the closed Maintenance Request plus an 'New' Maintenance Request of type 'Routine Maintenance' with the same Vehicle as the closed one.


I've checked several times. All seems right. I have a 'New' Maintenance Request of type 'Routine Maintenance' with the same Vehicle as the closed one.

Here is the closed maintenance request

User-added image

and here is the new maintenance request that has been automatically created

User-added image

Please help me :-). I want to have my superbadge :-)
Abhishek Malik 9Abhishek Malik 9
Hi adam can you please send me the code for APEX SUPERBADGE "Automate record creation" actully am trying the problem but unable to solve
please send me the code , please help am new to salesforce.
Jeff DouglasJeff Douglas
Yogesh, yes you'll need to make that change to the picklist values.

Jeff Douglas
Trailhead Developer Advocate
Jeff DouglasJeff Douglas
ODagneaux99, 

If you want to post your trigger's helper class here I can take a peek at it and give you some feedbck.

 
ODagneaux99ODagneaux99
Here is my code 
 
public class MaintenanceRequestHelper {
    
     public static void updateWorkOrders(Map<Id, case> applicableCases){
        
         list<sObject> allObjects = new list<sObject>();
         
         // Get the maintenance_cycle of the product for each product
         list<Product2> listProduct = [select Id, Maintenance_Cycle__c from Product2];  
         Map<Id,decimal> mapProduct = new Map<Id, decimal>();
         for (Product2 p : listProduct) {
             if (p != null) {
                 mapProduct.put(p.Id, p.Maintenance_Cycle__c);
             }
         }
         
         // For each case, create a new 'Routine Maintenance' case
         for (Case o : applicableCases.values()) 
         {
             Case a = new Case();
             
             a.RecordTypeId = '01258000000EG38'; // Id of a Routine Maintenance record type
             a.Subject = 'Routine Maintenance';
             a.Date_Reported__c = Date.today();
             a.Date_Due__c = Date.today();
             // Add the number of days of the Maintenance_Cyle
             if (mapProduct.get(o.Equipment__c) != null) {
                a.Date_Due__c += Integer.valueOf(mapProduct.get(o.Equipment__c));
             }
             a.Vehicle__c = o.Vehicle__c;
             a.Product__c = o.Product__c;
             a.ContactId = o.ContactId;
             a.AccountId = o.AccountId;
             a.AssetId = o.AssetId;
             
             if (o.recordTypeId=='01258000000EG33') {
                 a.Origin = 'Repair';
             } else {
                 a.Origin = 'Routine Maintenance';
             }
             a.Type = 'Routine Maintenance';
             
             allObjects.add(a);
             
          }//end for o
    
          try {
            insert allObjects;
          } catch (system.Dmlexception e) {
            system.debug (e);
          } 
    }        
    
}

 
ODagneaux99ODagneaux99
And my trigger is 
 
trigger MaintenanceRequest on Case (before update, after update) {
    
    System.debug('Je passe dans mon trigger');
    
	Map<Id, case> applicableCases = new Map<Id, case>();
    
    if (Trigger.isUpdate) {
        if (Trigger.isAfter) {

             for(Case a : Trigger.new)
             {
                 if(a.IsClosed && (a.type == 'Repair' || a.type =='Routine Maintenance'))
                 {
                       applicableCases.put(a.id, a);
                         
                       System.debug('Case applicable :' + a.CaseNumber);
                 }
             }
        }
    }
            
    MaintenanceRequestHelper.updateWorkOrders(applicableCases);
    
}

 
Jeff DouglasJeff Douglas
Your helper code looks good in general however there are a couple of things you'll want to change.
  1. No need to use Record Types. Just set the Type value to "Routine Maintenance". 
  2. Set the Status to "New".
  3. Set the Equipment__c field to the original equipment.
  4. The Date_Reported__c should be today's date plus the number of days of the Work Part's maintenance cycle.
HTH, if not, go ahead and post your new helper code.

Jeff Douglas
Trailhead Developer Advocate
Yogesh DYogesh D
Hi ODagneaux99,

Below is my code using which I was able to complete the challenge. You are almost there and seems that there are minor changes that needs to be done.  Below is the code which creates and inserts new Maintenance Requests (Cases).
for(Case eachCase : closedMaintenanceRequestList)
            {
                Case newCase = new Case();
                newCase.Type = 'Routine Maintenance';
                newCase.Status = 'New';
                newCase.Vehicle__c = eachCase.Vehicle__c;
                newCase.Product__c = eachCase.Product__c;
                newCase.Subject =  String.isBlank(eachCase.Subject) ?'Routine maintenance request':eachCase.Subject;
                newCase.Date_Reported__c = Date.today();
                newCase.Date_Due__c = Date.today().addDays(Integer.valueOf(eachCase.Maintenance_Cycle_Days_Case__c));
                newCase.Old_Case__c = eachCase.Id;
                newCase.AccountId = eachCase.AccountId;
                newCase.Origin = eachCase.Origin;
                newCase.Equipment__c = eachCase.Equipment__c;
                insertCaseList.add(newCase);
            }

Challenge does not complete just by doing this much.... as we also have to update the Work Parts that were related to the closed case and now update there association from closed csae to the newly created case. Below is the code snippet that does this....
for(Case eachCase : insertCaseList)
            {
                oldCaseIdtoNewCaseIdMap.put(eachCase.Old_Case__c, eachCase.Id);
            }

            relatedWorkParts = [Select Equipment__c, Maintenance_Request__c, Quantity__c 
                                From Work_Part__c Where Maintenance_Request__c In :closedMaintenanceRequestList];

            if(relatedWorkParts != null)
            {
                for(Work_Part__c eachWorkPart : relatedWorkParts)
                {
                    Id newCaseId = oldCaseIdtoNewCaseIdMap.get(eachWorkPart.Maintenance_Request__c);
                    
                    eachWorkPart.Maintenance_Request__c = newCaseId;
                }

                update relatedWorkParts;    
            }
Here one tricky thing is that you need to store the id of the closed case on the new csae that you are creating. For this I have created a new field (Old_Case__c) in which I store the id Lines which handle this part I have made them bold and italic. Let me know if this helps.

 
Sudipta DebSudipta Deb
Hi All -

There are few tricks in this assignment.
  • New Case's Reported Date shoulyd be Today's Date
  • New Case's Due Date should be Today's Date + Shortest Maintenance Cycle from the related Work Parts/Equipments(Products)
  • You need to add two picklist values in Case Type Picklist - "Routine Maintenance" & "Repair"
  • You need to create a custom field named "Old Case" to store the new case's ID in the newly created case (Though this requirement is not mentioned, but it will help you to achieve the requirement)
With these, below code -
Trigger Code -
trigger MaintenanceRequest on Case (before update, after update) {
    if(Trigger.isAfter && Trigger.isUpdate){
    	MaintenanceRequestHelper.updateAfterUpdateActivity(Trigger.new, Trigger.oldMap);
    		
    }
    
}

Helper Code -
public class MaintenanceRequestHelper {
    private static List<Case> closedCases = new List<Case>();
    private static List<Case> newlyCreatedCases = new List<Case>();
    private static List<Work_Part__c> allWorkParts = new List<Work_Part__c>();

    public static void updateWorkOrders(){
        // update workorders
    }        

    public static void updateAfterUpdateActivity(List<Case> newCases, Map<Id, Case> oldCases){
    	for(Case singleCase : newCases){
	    	if(singleCase.status == 'Closed' && oldCases.get(singleCase.ID).status != singleCase.status){
	    		if(singleCase.Type == 'Repair' || singleCase.Type == 'Routine Maintenance'){
	    			closedCases.add(singleCase);
	       		}
	    	}
	    }
	    createFollowUpMaintenanceRequest();
    }

    private static void createFollowUpMaintenanceRequest(){
    	Set<ID> caseIds = new Set<ID>();
    	for(Case singleCase : closedCases){
    		caseIds.add(singleCase.Id);
    	}
    	Integer shortestMaintCycle;
    	
    	Map<Id, List<Work_Part__c>> maintWorkPartMap = createMaintWorkPartMap(caseIds);

    	for(Case singleCase : closedCases){
    		List<Work_Part__c> workParts = maintWorkPartMap.get(singleCase.Id);
    		if(workParts != null){
    			shortestMaintCycle = Integer.valueOf(findShortestMaintCycle(workParts));	
    		}else{
    			shortestMaintCycle = Integer.valueOf(0.0);
    		}
    		

    		Case newCase = new Case();
    		newCase.Vehicle__c = singleCase.Vehicle__c;
    		newCase.Type = 'Routine Maintenance';
    		newCase.status = 'New';
    		newCase.Origin = singleCase.Origin;
    		newCase.Reason = singleCase.Reason;
    		newCase.Subject = String.isBlank(singleCase.Subject) ? 'Routine Maintenance Request' :
    			singleCase.Subject;
    		newCase.Date_Reported__c = Date.today();
    		newCase.Date_Due__c = Date.today().addDays(shortestMaintCycle);
    		newCase.Equipment__c = singleCase.Equipment__c;
    		newCase.Old_Case__c = String.valueOf(singleCase.Id);
    		newlyCreatedCases.add(newCase);
    	}

    	if(newlyCreatedCases.size() > 0){
    		insert newlyCreatedCases;
    		updateRelatedWorkOrders(newlyCreatedCases);
    	}
    }

    private static void updateRelatedWorkOrders(List<Case> cases){
    	Map<Id, Id> oldToNewCaseMap = new Map<Id, Id>();
    	for(Case singleCase : cases){
    		oldToNewCaseMap.put(Id.valueOf(singleCase.Old_Case__c),singleCase.Id);
    	}

    	if(allWorkParts != null){
    		for(Work_Part__c singleWorkPart : allWorkParts){
    			Id newCaseId = oldToNewCaseMap.get(singleWorkPart.Maintenance_Request__c);
    			singleWorkPart.Maintenance_Request__c = newCaseId;
    		}
    	}

    	if(allWorkParts != null && allWorkParts.size() > 0){
    		update allWorkParts;
    	}
    }

    private static Decimal findShortestMaintCycle(List<Work_Part__c> workParts){
    	Decimal shortestValue;
    	if(workParts.size()>0){
    		shortestValue = workParts.get(0).Equipment__r.Maintenance_Cycle__c;
    	}
    	for(Work_Part__c singleWorkPart : workParts){
    		if(singleWorkPart.Equipment__r.Maintenance_Cycle__c < shortestValue){
    			shortestValue = singleWorkPart.Equipment__r.Maintenance_Cycle__c;
    		}
    	}
    	return shortestValue;
    }

    private static Map<Id, List<Work_Part__c>> createMaintWorkPartMap(Set<ID> caseIds){
    	//Fetch all WorkPart details
    	allWorkParts = [SELECT ID, Equipment__c, Maintenance_Request__c, 
    			Quantity__c, Equipment__r.Maintenance_Cycle__c FROM Work_Part__c 
    			WHERE Maintenance_Request__c in: caseIds];
    	Map<Id, List<Work_Part__c>> maintWorkPartMap = new Map<Id, List<Work_Part__c>>();
    	for(Work_Part__c singleWorkPart : allWorkParts){
    		List<Work_Part__c> tempList;
    		if(maintWorkPartMap.get(singleWorkPart.Maintenance_Request__c) == null){
    			tempList = new List<Work_Part__c>();
    		}else{
    			tempList = maintWorkPartMap.get(singleWorkPart.Maintenance_Request__c);
    		}
    		tempList.add(singleWorkPart);
    		maintWorkPartMap.put(singleWorkPart.Maintenance_Request__c, tempList);
    	}

    	return maintWorkPartMap;
    }
    
}

Please let me know if you find the scope of improvement in the code. 

With regards,
Sudipta Deb
James EllisJames Ellis
make sure you enable reparenting on the maintenance_request__c field ...... ;-) otherwise you'll hit an 'Field is not writeable: Work_Part__c.Maintenance_Request__c' error
Venkatesan SundaramVenkatesan Sundaram
You do not believe that I wasted more than an hour due a silly spelling mistake. I created a new Case with Type as "Routine Maintenence" instead of "Routine Maintenance". Sharing it as it might help anyone else like me :)
SelvaaSelvaa
Hi ,

Am not able to complete the challenge for apex specialist,


i got error like below
 " Challenge Not yet complete... here's what's wrong: 
Inserting a new Maintenance Request of type 'Routine Maintenance' and then closing it did not create of a new Maintenance Request based upon the original record correctly. The challenge is expecting to find the closed Maintenance Request plus an 'New' Maintenance Request of type 'Routine Maintenance' with the same Vehicle as the closed one."
SelvaaSelvaa
public class MaintenanceRequestHelper {

    public static void updateWorkOrders(Map<Id, Case>  cases){
        List<Case> maintenance_routineList = new List<Case>();

        List<Product2> listProduct = [select Id, Maintenance_Cycle__c from Product2];  
        Map<Id,decimal> mapProduct = new Map<Id, decimal>();
        
        for (Product2 p : listProduct) {
            if (p != null) {
                if(p.Maintenance_Cycle__c != null){
                    mapProduct.put(p.Id, p.Maintenance_Cycle__c);
                }               
            }
        }

        System.debug('### product: '+mapProduct);

        for(Case maintenance:cases.values()){
            Case maintenanceNew = new Case();
            maintenanceNew.Subject = 'Routine Maintenance';
            System.debug('### Second: '+mapProduct.get(maintenance.Equipment__c));
            if (mapProduct.get(maintenance.Equipment__c) != null) {
                
                 maintenanceNew.Date_Due__c = Date.today().addDays(Integer.valueOf(mapProduct.get(maintenance.Equipment__c)));
                     
            }
            maintenanceNew.Vehicle__c = maintenance.Vehicle__c;
            maintenanceNew.Product__c = maintenance.Product__c;
            maintenanceNew.ContactId  = maintenance.ContactId;
            maintenanceNew.AccountId  = maintenance.AccountId;
            maintenanceNew.AssetId    = maintenance.AssetId;
            maintenanceNew.Type       = 'Routine Maintenance';
            maintenanceNew.Status     = 'New';
            maintenanceNew.Equipment__c = maintenance.Equipment__c;
            maintenanceNew.Date_Reported__c = Date.today();


            maintenance_routineList.add(maintenanceNew);
        }

        insert maintenance_routineList;
    }
}


/// Trigger 
trigger MaintenanceRequest on Case (after update) {
    
    //List<Case> casesToEvaluate = new List<Case>();
    Map<Id, Case> casesToEvaluate = new Map<Id, Case>();

    if(Trigger.isAfter && Trigger.isUpdate){
        for(Case maintenance:Trigger.new){
            if((maintenance.Type.contains('Repair') || maintenance.Type.contains('Routine Maintenance')) && maintenance.Status == 'Closed'){
                casesToEvaluate.put(maintenance.Id,maintenance);
            }
        }       
    }
    MaintenanceRequestHelper.updateWorkOrders(casesToEvaluate);
}

 
Apurv SaxenaApurv Saxena
Can anyone help me with the test class of the trigger? This is my code but I am unable to cover my methods.
@isTest
public class MaintenanceRequesTest {
    @isTest
    static void testMaintenanceRequest(){
        
        List<case> caseList1 = new List<case>();
        List<case> caseList2 = new List<case>();
        
        for(Integer i=0;i<200;i++){
            Case c = new Case();
            c.Status = 'Closed';
            c.Type = 'Repair';
            c.Vehicle__c = c.Id;
            caseList1.add(c);
        }
        for(Integer j=0;j<200;j++){
            Case c = new Case();
            c.Status = 'Closed';
            c.Type = 'Routine Maintenance';
            c.Vehicle__c = c.Id;
            caseList2.add(c);
        }
        caseList1.addAll(caseList2);
        if(caseList1.size()>0){
        	insert caseList1;    
        }
        
    }
}

Thanks in advance
BAILA TOUREBAILA TOURE
Below my code test class. Hop this will help u 
@isTest
public class MaintenanceRequesTest {
    @testSetup static void methodName() {
        List<Vehicle__c> vehiculeList = new List<Vehicle__c>();
        List<Product2> Product2List = new List<Product2>();
        List<Work_Part__c> partsList = new List<Work_Part__c>();
        List<case> caseList1 = new List<case>();
        List<case> caseList2 = new List<case>();
        
        try {
        Vehicle__c veh1 = new Vehicle__c (Model__c='Vehic1');
        Vehicle__c veh2 = new Vehicle__c (Model__c='Vehic2');
            Product2 prod = new Product2 (Name='Product1');
            prod.Maintenance_Cycle__c =10;
            insert prod;
        
        vehiculeList.add(veh1);
        vehiculeList.add(veh2);
            insert vehiculeList;
        
        for(Integer i=0;i<200;i++){
            Case c = new Case();
            c.Status = 'Open';
            c.Type = 'Repair';
            c.Vehicle__c = veh1.Id;
            caseList1.add(c);
        }
        for(Integer j=0;j<200;j++){
            Case c = new Case();
            c.Status = 'Open';
            c.Type = 'Routine Maintenance';
            c.Vehicle__c = veh2.Id;
            caseList2.add(c);
        }
        caseList1.addAll(caseList2);
        if(caseList1.size()>0){
            insert caseList1;  
            Work_Part__c part = new Work_Part__c ();
             Work_Part__c part0 = new Work_Part__c ();
            Case case1 = [Select id from Case where Vehicle__c =:veh1.Id Limit 1];
            Case case2 = [Select id from Case where Vehicle__c =:veh2.Id Limit 1];
             Product2 prod0 = [Select id from Product2 where Name ='Product1'];
            part.Equipment__c = prod0.Id;
            part.Maintenance_Request__c = case1.Id;            
            partsList.add(part);
            part0.Equipment__c = prod0.Id;
            part0.Maintenance_Request__c = case1.Id;            
            partsList.add(part0);
            insert partsList;           
                        
        }
        
            
        }catch (System.DmlException e) {
    
        System.debug(e.getMessage()); 
    }
       
    }
     @isTest
    static void testMaintenanceRequest(){
        //Close Cases
            List<case> closedCaseList1 = new List<case>();
           List<case> closedCaseList2 = new List<case>();
             Vehicle__c veh1 = [Select id from Vehicle__c where Model__c='Vehic1'];
            closedCaseList1 = [Select id, Status from Case where Vehicle__c =:veh1.Id];
            
            for(Case c : closedCaseList1){
                c.Status ='Closed';
                closedCaseList2.add(c);
            }
            update closedCaseList2;

    }
}
   
        
     

 
Kellan ScheiberKellan Scheiber
Here is the code I used to pass the challenge, a little bit more succinct that others I have seen. Ensure after update and after insert for trigger. Hope this helps anyone stuck. One issue I was stuck on is passing value of oldCase list in static methods so I had to recreate list in helper method to get date.
trigger MaintenanceRequest on Case (after update, after insert) {
    
    Public List<Case> closedCase = new List<Case>();
    for(List<Case> a : [select ID, vehicle__c, equipment__c, date_due__c from Case Where Id IN :Trigger.new AND status = 'Closed' and Type IN ('Repair', 'Routine Maintenance')]) {
        closedCase = a;
        MaintenanceRequestHelper.updateWorkOrders(closedCase);
    }
             
}
 
public class MaintenanceRequestHelper {
    
    Public Static List<Case> oldCase = new List<Case>();
    
    public static void updateWorkOrders(List<Case> closedCase){
        oldCase = closedCase;
   		List<Case> newCase = new List<Case>();
    		for (Case newCase2 : oldCase) {
            			newCase.add(new Case(type = 'Routine Maintenance',
                                status = 'New',
                                origin = 'Web',
                                Subject = null,
                                Date_Reported__c = date.today(),
                                Vehicle__c = newCase2.Vehicle__c,
                                Equipment__c = newCase2.Equipment__c,
                                Date_Due__c = cycleCalc2()));   
        }
        insert newCase;
    }
    
    private static Date cycleCalc2() {
        oldCase = [select ID from Case Where status = 'Closed' and Type IN ('Repair', 'Routine Maintenance')];
        AggregateResult[] minCycleDay2 = [Select min(Equipment__r.Maintenance_Cycle__c) FROM Work_Part__c WHERE Equipment__r.Maintenance_Cycle__c != null
                                         AND Maintenance_Request__c IN: oldCase];
        Integer minCycleNum = ((Decimal)minCycleDay2[0].get('expr0')).intValue();
        Date returnDate = date.Today() + minCycleNum;
        return returnDate;
               
    	}
	}
Nithesh NNithesh N
Hi All, I was able to Clear My challenge with this Code. 

Trigger:
 
trigger MaintenanceRequest on Case (before update, after update) {  
    List<case>ClosedCaseList = [SELECT Id, subject,Reason, Vehicle__c, vehicle__r.Name, equipment__c,type 
                                FROM Case WHERE Id IN :Trigger.New 
                                AND (status = 'closed' AND (type = 'Repair' OR type = 'Routine Maintenance'))];   
    Map<Id, Case>CasesToConsider = new Map<Id, Case>();
    for(Case c: ClosedCaseList){
        Boolean alreadyClosed = Trigger.oldMap.get(c.Id).Status.equals('Closed') ;
        if(!alreadyClosed)
        {
            CasesToConsider.put(c.id, c);
        }
    }
    
    List<Work_Part__c> allWorkParts = [SELECT ID, Equipment__c, Maintenance_Request__c, 
    			Quantity__c, Equipment__r.Maintenance_Cycle__c FROM Work_Part__c 
    			WHERE Maintenance_Request__c in: CasesToConsider.keySet()];
    
    MaintenanceRequestHelper.updateWorkOrders(CasesToConsider, allWorkParts);       
}

Helper:
 
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(Map<Id, Case>CasesMap, List<Work_Part__c> WorkParts){
        // update workorders
        Decimal shortestCycle;
        List<Work_Part__c> allWorkParts = workParts;
        List<Case> casesToCreate = new List<Case>();
        for(Case c : CasesMap.values()) {
            List<Work_Part__c> relatedWorkParts = new List<Work_Part__c>();
            for(Work_Part__c workpart: WorkParts){                
                if(c.Id == workpart.Maintenance_Request__c){
                    relatedWorkParts.add(workpart);
                }
            }            
            shortestCycle = getMaintainCycle(relatedWorkParts);
            Case newCase = new Case();
    		newCase.Vehicle__c = c.Vehicle__c;
    		newCase.Type = 'Routine Maintenance';
    		newCase.status = 'New';
    		newCase.Reason = c.Reason;
    		newCase.Subject = String.isBlank(c.Subject) ? 'Routine Maintenance Request' :
    			c.Subject;
    		newCase.Date_Reported__c = Date.today();
    		newCase.Date_Due__c = Date.today().addDays( Integer.valueOf(shortestCycle));
    		newCase.Equipment__c = c.Equipment__c;
    		newCase.Old_Case__c = c.Id;
    		casesToCreate.add(newCase);
			            
        }  
        if(casesToCreate.size() > 0){
            insert casesToCreate;
            updateRelatedWorkOrders(casesToCreate, allWorkParts);
        }
    }
    
    public static Decimal getMaintainCycle(List<Work_Part__c> WorkParts){
        Decimal maintainCycle;
        List<Decimal> cycleList = new List<Decimal>();
        if(WorkParts.size() >0){
            for(Work_Part__c part: WorkParts){
                cycleList.add(part.Equipment__r.Maintenance_Cycle__c);
                cycleList.sort();
            }
        }
        
        if(cycleList.size() > 0){
            maintainCycle = cycleList.get(0);
        }
        else{
            maintainCycle = 0.0;
        }
        return maintainCycle;        
    }
    
     private static void updateRelatedWorkOrders(List<Case> cases, List<Work_Part__c> allWorkParts){
    	Map<Id, Id> oldToNewCaseMap = new Map<Id, Id>();
    	for(Case singleCase : cases){
    		oldToNewCaseMap.put(singleCase.Old_Case__c,singleCase.Id);
    	}

    	if(allWorkParts != null){
    		for(Work_Part__c singleWorkPart : allWorkParts){
    			Id newCaseId = oldToNewCaseMap.get(singleWorkPart.Maintenance_Request__c);
    			singleWorkPart.Maintenance_Request__c = newCaseId;
    		}
    	}

    	if(allWorkParts != null && allWorkParts.size() > 0){
    		update allWorkParts;
    	}
    }
    
}

Make sure to add
* Two picklist values in Case Type Picklist - "Routine Maintenance",  "Repair"
* A Custom field named "Old Case" (Lookup to Case) to store the new case's ID.
Anup KabraAnup Kabra
Hi All,

I tried with lot of different codes but I am stuck with weird error. It doesnt say much except :

MaintenanceRequest                    Line 0                                invalid parameter value

I am using the same code as Nithesh N.

Please let me know if someone else has encountered the same problem.
 
Anup KabraAnup Kabra
I used trailhead playground and din't get this issue anymore :)
Darrell GallegosDarrell Gallegos
I cannot for the life of me wrap my head around why my code is creating multiple "New" cases after an existing case Status is set to 'Closed' given the criteria. Below is my Helper Class and Trigger. I passed the challege but I am creating multiple New Cases every time I close one.
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(){
        
        List<Case> closedReqs = [SELECT Id, Vehicle__c, Equipment__c, Type,Status,Origin, Subject, (Select Id, Routine_Replace__c From Work_Parts__r) FROM Case WHERE isClosed = true];
        
        List<Case> createNewCase = new List<Case>();
        
        for (Case mainRequests : closedReqs) {
            if(mainRequests.type == 'Repair' || mainRequests.type == 'Routine Maintenance') {
                
                Case newMainReq = new Case();
                    newMainReq.Vehicle__c = mainRequests.Vehicle__c;
                    newMainReq.Type = 'Routine Maintenance';
                    newMainReq.Equipment__c = mainRequests.Equipment__c;
                    newMainReq.Status = 'New';
                    newMainReq.Origin = 'Email';
                    newMainReq.Subject = 'Scheduled Maintenance';
                	newMainReq.Date_Reported__c = System.today();
                	newMainReq.Date_Due__c = System.today() + 30; // mainRequests.Work_Parts__r.Routine_Replace__c;
                	createNewCase.add(newMainReq);
                    
            }
        }                             
    	
    insert createNewCase;
    }   
}
 
trigger MaintenanceRequest on Case (before update, after update) {
    
    for(Case myCases : Trigger.new) {
        if(Trigger.oldMap.get(myCases.Id).Status != 'Closed') {
            if(Trigger.isUpdate || Trigger.isAfter) {
                // call MaintenanceRequestHelper.updateWorkOrders
                MaintenanceRequestHelper.updateWorkOrders();
            }
        }
    }
}

If anybody could assist that would be AWESOME. I know my date is not correct but I will work on that. I am simply seeking assistance to deter from creating multiple New Cases

THANKS 
 
Luca BassaniLuca Bassani
Hi guys, here my work...I can't see any problem, any idea about? ​(It fails in Check Challenge)
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(Map<Id,Case> oldCases, Map<Id,Case> newCases){
        Map<Id,Case> caseIdCase = new Map<Id,Case>();
        List<Case> caseToInsert = new List<Case>();
        for(Case c: newCases.values()){
            if((c.Type == 'Repair' || c.Type == 'Routine Maintenance') && 
                c.Status != oldCases.get(c.Id).Status &&
                c.Status == 'Closed'){
                caseIdCase.put(c.Id,c);
            }
        }
        List<Work_Part__c> wps = [SELECT Id,Maintenance_Request__c,Equipment__r.Maintenance_Cycle__c 
                                  FROM Work_Part__c 
                                  WHERE Maintenance_Request__c in :caseIdCase.keySet()];
        System.debug('Work Parts: ' + wps);
        Map<Id,Decimal> caseIdMinMaintenanceCycle = new Map<Id,Decimal>();
        for(Work_Part__c wp : wps){
            if(!caseIdMinMaintenanceCycle.containsKey(wp.Maintenance_Request__c) || 
                (caseIdMinMaintenanceCycle.get(wp.Maintenance_Request__c) > wp.Equipment__r.Maintenance_Cycle__c)){
                caseIdMinMaintenanceCycle.put(wp.Maintenance_Request__c,wp.Equipment__r.Maintenance_Cycle__c);
            }
        }
        System.debug('caseIdMinMaintenanceCycle: ' + caseIdMinMaintenanceCycle);
        for(Id caseId : caseIdMinMaintenanceCycle.keySet()){
            Case c = caseIdCase.get(caseId);
            caseToInsert.add(
                new Case(
                    Reason = 'Other',
                    Origin = 'Auto',
                    Status = 'New',
                    Subject = 'Scheduled Maintenance',
                    Type = 'Routine Maintenance',
                    Date_Reported__c = Date.today(),
                    Date_Due__c = Date.today().addDays((Integer) caseIdMinMaintenanceCycle.get(caseId)),
                    AccountId = c.AccountId,
                    Vehicle__c = c.Vehicle__c,
                    ParentId = c.Id
                )
            );
        }
        System.debug('caseToInsert: ' + caseToInsert);
        if(!caseToInsert.isEmpty()){
            insert caseToInsert;
        }
    }        
}
Many thanks,
Luca
Darrell GallegosDarrell Gallegos
@Luca

What is the error you are getting? That will help troubleshoot. Also post your Trigger as well.
Luca BassaniLuca Bassani

I dont remember the previous message, it was something like "there is something wrong", but with no helpfull description

Now I've received this one:
"Challenge Not yet complete... here's what's wrong: 
Inserting a new Maintenance Request of type 'Routine Maintenance' and then closing it did not create of a new Maintenance Request based upon the original record correctly. The challenge is expecting to find the closed Maintenance Request plus an 'New' Maintenance Request of type 'Routine Maintenance' with the same Vehicle as the closed one."


I've tried to replicate it manually and the trigger works fine.

Here the trigger:

trigger MaintenanceRequest on Case (before update, after update) {
    if(Trigger.isBefore && Trigger.isUpdate){
        MaintenanceRequestHelper.updateWorkOrders(Trigger.oldMap,Trigger.newMap);
    }
}
 

Thanks again :)
Luca

Kellan ScheiberKellan Scheiber
Darrell,

Try adjusting your trigger to Before Insert, Before Update.

I wonder if before update, and after update is causing the trigger to execute mulitiple times and inserting multiple cases.
Kellan ScheiberKellan Scheiber
Luca/Darrell,

I wonder if your trigger is having the same issue. Try After Insert, After update after going back and reviewing the challenge.

That may clear up both your issues.

 
Luca BassaniLuca Bassani

Hi guys,

I've handle only the UPDATE, because the request is to fire an action when Mantainance Request's Status changes to 'Closed'.
My action is create a new Maintenance Request with Status 'New', so that it'll never create a loop.
I've tried to use AFTER Trigger but I receive the same error.

Have you got any idea?

Luca :)
 

Kellan ScheiberKellan Scheiber
I would still trigger on After insert because the external system may be loading cases in a closed status has an hypothetical.

The error spefically states "Inserting a new Maintenance Request of type 'Routine Maintenance' " so it is probably checking inserting with closed status and not triggering
Luca BassaniLuca Bassani

Nice idea Kellan,

I've changed the logic in order to handle also the After Insert Event, but nothing append...Here the new version of my class

public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(Map<Id,Case> oldCases, Map<Id,Case> newCases){
        Map<Id,Case> caseIdCase = new Map<Id,Case>();
        List<Case> caseToInsert = new List<Case>();
        
        for(Id caseId : newCases.keySet()){
            Boolean hasPrevious = oldCases.get(caseId) != null;
            Boolean isClosed = newCases.get(caseId).Status == 'Closed' 
                && (!hasPrevious || (hasPrevious && oldCases.get(caseId).Status != newCases.get(caseId).Status));
            Boolean isRepairOrMaintenance = newCases.get(caseId).Type == 'Repair' || newCases.get(caseId).Type == 'Routine Maintenance';
            System.debug('isClosed: ' + isClosed  + ' isRepairOrMaintenance: '+ isRepairOrMaintenance);
            
            if(isRepairOrMaintenance && isClosed){
                caseIdCase.put(caseId, newCases.get(caseId));
            }
        }
        System.debug('caseIdCase: ' + caseIdCase);
        List<Work_Part__c> wps = [SELECT Id,Maintenance_Request__c,Equipment__r.Maintenance_Cycle__c 
                                  FROM Work_Part__c 
                                  WHERE Maintenance_Request__c in :caseIdCase.keySet()];
        System.debug('Work Parts: ' + wps);
        Map<Id,Decimal> caseIdMinMaintenanceCycle = new Map<Id,Decimal>();
        for(Work_Part__c wp : wps){
            if(!caseIdMinMaintenanceCycle.containsKey(wp.Maintenance_Request__c) || 
                (caseIdMinMaintenanceCycle.get(wp.Maintenance_Request__c) > wp.Equipment__r.Maintenance_Cycle__c)){
                caseIdMinMaintenanceCycle.put(wp.Maintenance_Request__c,wp.Equipment__r.Maintenance_Cycle__c);
            }
        }
        System.debug('caseIdMinMaintenanceCycle: ' + caseIdMinMaintenanceCycle);
        for(Id caseId : caseIdMinMaintenanceCycle.keySet()){
            Case c = caseIdCase.get(caseId);
            caseToInsert.add(
                new Case(
                    Reason = 'Other',
                    Origin = 'Auto',
                    Status = 'New',
                    Subject = 'Scheduled Maintenance',
                    Type = 'Routine Maintenance',
                    Date_Reported__c = Date.today(),
                    Date_Due__c = Date.today().addDays((Integer) caseIdMinMaintenanceCycle.get(caseId)),
                    AccountId = c.AccountId,
                    Vehicle__c = c.Vehicle__c,
                    ParentId = c.Id
                )
            );
        }
        System.debug('caseToInsert: ' + caseToInsert);
        if(!caseToInsert.isEmpty()){
            insert caseToInsert;
        }
    }        
}
 

Many thanks,

Luca

 

t j 5t j 5
Check this link https://developer.salesforce.com/forums/?id=906F0000000kJtCIAU#!/feedtype=SINGLE_QUESTION_DETAIL&dc=Trailhead&criteria=OPENQUESTIONS&id=9060G000000MOtYQAW
Ankit Maini.Ankit Maini.
Here is my solution: Passed
Trigger:
trigger MaintenanceRequest on Case (before update, after update) {
    // call MaintenanceRequestHelper.updateWorkOrders
    if(Trigger.isUpdate && Trigger.isAfter) {
        List<Case> newCaseList = new List<Case>();
        Set<Case> closedCase = new Set<Case>(); 
        for(Case ca: Trigger.new) {
            if(ca.Status == 'Closed' && (ca.Type == 'Repair' || ca.Type == 'Routine Maintenance')) {
                closedCase.add(ca);
				
            }
        }
        
        List<Work_Part__c> workPartList = [SELECT Id,Equipment__r.Maintenance_Cycle__c,Maintenance_Request__c from Work_Part__c where Maintenance_Request__c in :closedCase];
        System.debug(workPartList);
        MaintenanceRequestHelper.updateWorkOrders(closedCase, workPartList);
       
    }  
}

Class: MaintenanceRequestHelper
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(){
        // update workorders
    }  
    public static void updateWorkOrders(Set<Case> closedCase, List<Work_Part__c> workPartList){
        List<Case> newCaseList = new List<Case>();
        Map<String, Decimal> mapOfCycle = getMapOfCycle(workPartList);
        for(Case ca : closedCase) {
            	Case newCase = new Case();
            	newCase.Status = 'New';
				newCase.Vehicle__c = ca.Vehicle__c;
				newCase.Type = 'Routine Maintenance'; 
                newCase.Subject = 'Routine Maintenance '+Date.today();
                newCase.Equipment__c = ca.Equipment__c;
                newCase.Date_Reported__c = Date.today();
                newCase.Date_Due__c = (mapOfCycle.containsKey(ca.Id) == true) ? Date.today().addDays(Integer.valueOf(mapOfCycle.get(ca.Id))) : null;
            	newCaseList.add(newCase);
        }
      
         if(newCaseList.size()>0) {
            insert newCaseList;
        }
    } 
    
    private static Map<String,Decimal> getMapOfCycle(List<Work_Part__c> workPartList){
         Map<String, Decimal> mapOfCycle = new Map<String,Decimal>();
          for(Work_Part__c wp : workPartList){
            system.debug('~~'+wp.Equipment__r.Maintenance_Cycle__c);
            if(wp.Equipment__r.Maintenance_Cycle__c != null) {
                if(mapOfCycle.containsKey(wp.Maintenance_Request__c)) {
                    Decimal cyc = mapOfCycle.get(wp.Maintenance_Request__c);
                    if(cyc > wp.Equipment__r.Maintenance_Cycle__c) {
                        mapOfCycle.put(wp.Maintenance_Request__c, wp.Equipment__r.Maintenance_Cycle__c);
                    }
                }
                else {
                    mapOfCycle.put(wp.Maintenance_Request__c, wp.Equipment__r.Maintenance_Cycle__c);
                }
            }
        }
        return mapOfCycle;
    }
}


 
SabinaSabina
Even though the requirements say to "create a Routine Maintenance request every time a maintenance request of type Repair or Routine Maintenance is updated to Closed", the validation was failing with the error

Inserting a new Maintenance Request of type 'Repair' and then closing it did not work as expected. The challenge was NOT expecting to find a Maintenance Request with the same Vehicle and the Status of 'New' and of Type 'Routine Maintenance'. However, it did.

After a couple of hours of debugging, I ruled out the "Repair" type from the criteria and then it passed. Way to go, Trailhead! :(
John Reed 7John Reed 7
Thanks all.  There was one place in the reqts I found a little confusing, Equipment is a lookup field on the Case/MR, but there is also an Equipment lookup in Work Parts.

Once I copied the Equipment field from the old Case/MR to the new Case/MR, I passed.  Suggest Updating the requirements and/or the Entity Diagram.  But maybe that is part of the challenge?

Also I added a formula field on Work Parts to pull in the Maintenance_Cycle_Days__c from Equipment.  That min bit isn't checked in the Check Challenge.

Passed step 1.  On to step 2, no time to REST! :-)
trigger MaintenanceRequest on Case (before update, after update) {
    Set<Id> caseIds = new Set<Id>();
    for (Case cs :Trigger.New) {
        If (Trigger.IsUpdate && Trigger.IsAfter &&
           (Trigger.oldMap.get(cs.Id).isClosed != Trigger.newMap.get(cs.Id).isClosed) &&
           cs.isClosed && (cs.Type == 'Routine Maintenance' || cs.Type == 'Repair')) {
        	caseIds.add(cs.Id);
        }
    }
    MaintenanceRequestHelper.updateWorkOrders(caseIds);
}

public class MaintenanceRequestHelper {
    public static void updateWorkOrders(Set<Id> caseIds) {
        List<Case> newCases = new List<Case>();
        List<Work_Part__c> newWorkParts = new List<Work_Part__c>();
        List<Case> oldCases = [select Id, Vehicle__c, Type, Status, Equipment__c,
                              (select Id, Maintenance_Cycle_Days__c from Work_Parts__r order by Maintenance_Cycle_Days__c ASC NULLS LAST)
                               From Case WHERE Id IN :caseIds];
        for (Case c :oldCases) {
            Case newCase = new Case(Vehicle__c = c.Vehicle__c, Equipment__c = c.Equipment__c, Type = 'Routine Maintenance', Status = 'New', Subject = 'Scheduled Maintenance', Date_Due__c = system.today() + 90, Date_Reported__c = system.today());
            if (c.Work_Parts__r.size() > 0) {
                newCase.Date_Due__c = system.today() + Integer.valueOf(c.Work_Parts__r[0].Maintenance_Cycle_Days__c);
                for (Work_Part__c wp :c.Work_Parts__r) {
                    Work_Part__c newWP = new Work_Part__c(Equipment__c = wp.Equipment__c, Maintenance_Request__c = newCase.Id);
                    newWorkParts.add(newWP);
                }
            }
            newCases.add(newCase);
        }
        insert newCases;
        insert newWorkParts;
    }
}

 
Matyas CsabaMatyas Csaba
I spent hours  trying to  get  it passed  I had the same issue as Sabina

"Even though the requirements say to "create a Routine Maintenance request every time a maintenance request of type Repair or Routine Maintenance is updated to Closed", the validation was failing with the error

Inserting a new Maintenance Request of type 'Repair' and then closing it did not work as expected. The challenge was NOT expecting to find a Maintenance Request with the same Vehicle and the Status of 'New' and of Type 'Routine Maintenance'. However, it did.

After a couple of hours of debugging, I ruled out the "Repair" type from the criteria and then it passed. Way to go, Trailhead! :("

Is the requqirement misleading?  
Aslo I noticed that  many people  wrote is need for reparentig the Work parts belonging to the OLD  case  with the New CASE.  Can somebody  tell me which  part  of  the requirement asks/suggest  this?    I my  opinion te new CASe  should  be created without  Work Parts  and only  in the Processign stage  of the Request the work part  should be added
 
Frederick H LaneFrederick H Lane
I just can't get my code to be accepted;
My script is;
_________________________________________________________________________________________
trigger MaintenanceRequest on Case (before update, after update) {
    Set<Id> caseIds = new Set<Id>();
    for (Case cs :Trigger.New) {
        If (Trigger.IsUpdate && Trigger.IsAfter &&
           (Trigger.oldMap.get(cs.Id).isClosed != Trigger.newMap.get(cs.Id).isClosed) &&
           cs.isClosed && (cs.Type == 'Routine Maintenance' || cs.Type == 'Repair')) {
            caseIds.add(cs.Id);
        }
    }
    MaintenanceRequestHelper.updateWorkOrders(caseIds);
}
Compile Error: Method does not exist or incorrect signature: void updateWorkOrders(Set<Id>) from the type MaintenanceRequestHelper at line 10 column 30

Then, for the MaintenanceRequestHelper Class;
______________________________________________________________________________________
public class MaintenanceRequestHelper {
    public static void updateWorkOrders(Set<Id> caseIds) {
        List<Case> newCases = new List<Case>();
        List<Work_Part__c> newWorkParts = new List<Work_Part__c>();
        List<Case> oldCases = [select Id, Vehicle__c, Type, Status, Equipment__c,
                              (select Id, Maintenance_Cycle_Days__c from Work_Parts__r order by Maintenance_Cycle_Days__c ASC NULLS LAST)
                               From Case WHERE Id IN :caseIds];
        for (Case c :oldCases) {
            Case newCase = new Case(Vehicle__c = c.Vehicle__c, Equipment__c = c.Equipment__c, Type = 'Routine Maintenance', Status = 'New', Subject = 'Scheduled Maintenance', Date_Due__c = system.today() + 90, Date_Reported__c = system.today());
            if (c.Work_Parts__r.size() > 0) {
                newCase.Date_Due__c = system.today() + Integer.valueOf(c.Work_Parts__r[0].Maintenance_Cycle_Days__c);
                for (Work_Part__c wp :c.Work_Parts__r) {
                    Work_Part__c newWP = new Work_Part__c(Equipment__c = wp.Equipment__c, Maintenance_Request__c = newCase.Id);
                    newWorkParts.add(newWP);
                }
            }
            newCases.add(newCase);
        }
        insert newCases;
        insert newWorkParts;
    }
}
ERROR at Row:2:Column:74
Didn't understand relationship 'Work_Parts__r' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 5 column 31
Charlotte Gibson 10Charlotte Gibson 10
The requirements on this one could have been better written. In particular "you need to calculate and set the next due date using the maintenance cycle defined on the related work part records". I did a subquery of work_parts__r from the case, but the tests run by SF didn't return any work_part records. Then when I arbitrarily decided to try assigning the maintenance cycle value from the case.equipment__c relationship, I cleared this step.

It would have really helped to see the test methods that were being run, so we could ascertain whether the error was due to our own code or the test being run by SF - aren't we supposed to be doing test-development anyway? ;-)
Muhammad Refaat 2Muhammad Refaat 2
 
trigger MaintenanceRequest on Case (before update, after update) {
    if (Trigger.isUpdate && Trigger.isAfter) {
        Map<Id, case> mapCases = new Map<Id, case>();
        for(Case c : Trigger.new){
            case oldC = Trigger.oldMap.get(c.Id);
            if(c.IsClosed && ! oldC.IsClosed  && (c.type == 'Repair' || c.type =='Routine Maintenance')){
                mapCases.put(c.Id,c);
            }
        }
        MaintenanceRequestHelper.updateWorkOrders(mapCases);

    }
}




 
public class MaintenanceRequestHelper {
    
    public static void updateWorkOrders(Map<Id, case> mapCases){
        map<Id,decimal> mapCaseCycle = new map<Id,decimal>();
        list<case> toCreate = new list<case>();        
        for(Work_Part__c wp: [select id,Maintenance_Request__c,Equipment__r.Maintenance_Cycle__c from Work_Part__c where Maintenance_Request__c in: mapCases.keySet() ]){
            decimal cycle = (wp.Equipment__r.Maintenance_Cycle__c==null?0:wp.Equipment__r.Maintenance_Cycle__c);              
            if(mapCaseCycle.get(wp.Maintenance_Request__c) != null){                
                mapCaseCycle.put(wp.Maintenance_Request__c,(cycle<mapCaseCycle.get(wp.Maintenance_Request__c)?cycle:mapCaseCycle.get(wp.Maintenance_Request__c)));
            } else {
                mapCaseCycle.put(wp.Maintenance_Request__c,cycle);
            }            
        }
        for(case c: mapCases.values()){
            toCreate.add(new Case(
                Subject ='Routine Maintenance',
                Type = 'Routine Maintenance',
                Date_Reported__c = Date.today(),
                Date_Due__c = mapCaseCycle.get(c.Id)==null?Date.today():Date.today().addDays(Integer.valueOf(mapCaseCycle.get(c.Id))),
                ParentId =c.Id,
                AccountId = c.AccountId,
                Origin = c.Origin ,
                Equipment__c = c.Equipment__c ,
                Vehicle__c = c.Vehicle__c                                
            ));
        }
        if(toCreate.size()>0){insert toCreate;}
       
    }        
    
}