• Mayank Parnami
  • NEWBIE
  • 0 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 1
    Replies
Test class is as follows(getting passed with 100% coverage) :-
@isTest
public class MaintenanceRequestTest {
    static  List<Case> caseList1 = new List<Case>();
    static List<Product2> prodList = new List<Product2>();
    static List<Equipment_Maintenance_Item__c> wpList = new List<Equipment_Maintenance_Item__c>();
    @testSetup
    static void getData(){
        caseList1= CreateData( 300,3,3,'Repair');
         System.assertEquals(300, caseList1.size());  
    }    
    public static List<Case>
    CreateData( Integer numOfcase, Integer numofProd, Integer numofVehicle,
    String type){
        List<Case> caseList = new List<Case>();
        //Create Vehicle       
        Vehicle__c vc = new Vehicle__c();
        vc.name='Test Vehicle';
        upsert vc;
        //Create Equipment
        for(Integer i=0;i<numofProd;i++){
            Product2 prod = new Product2();
            prod.Name='Test Product'+i;
            if(i!=0)
            prod.Maintenance_Cycle__c=i;
            prod.Replacement_Part__c=true;
            prodList.add(prod);
        }
        system.debug('prodList.size()'+prodList.size());
           system.assertEquals(prodList.size(), 3);
        upsert prodlist;
        //Create Case
        for(Integer i=0;i< numOfcase;i++){
            Case newCase = new Case();
            newCase.Status='New';
            newCase.Origin='web';
            if( math.mod(i, 2) ==0)
            newCase.Type='Routine Maintenance';
            else
            newCase.Type='Repair'; 
            newCase.Subject='Routine Maintenance of Vehicle' +i;
            newCase.Vehicle__c=vc.Id;
            if(i<numofProd)
            newCase.productid=prodList.get(i).ID;
            else 
            newCase.productid=prodList.get(0).ID;
            caseList.add(newCase);
        }
         system.debug('caseList.size()  *'+caseList.size());
          system.assertEquals(caseList.size(), 300);
        upsert caseList;       
        //create work part                               
        for(Integer i=0;i<numofProd;i++){                           
            Equipment_Maintenance_Item__c wp = new Equipment_Maintenance_Item__c();
            wp.Equipment__c   =prodlist.get(i).Id   ; 
            wp.Maintenance_Request__c=caseList.get(i).id;
            wplist.add(wp) ;
        }
         system.debug('wplist.size() *'+wplist.size());
         system.assertEquals(wplist.size(), 3);
        upsert wplist;
        system.debug('caseList *'+caseList);
        return caseList;              
    }      
    public static testmethod void testMaintenanceHelper(){        
        Test.startTest();
        getData();
        for(Case cas: caseList1)   
        cas.Status ='Closed';  
        System.assertEquals(300, caseList1.size());    
        update caseList1;  
       
            List<Case> allCases = [SELECT ID,Date_Due__c FROM Case WHERE status = 'New'];
            System.assertEquals(600, allCases.size() );
            system.debug('allCases in debug'+allCases );
            system.debug('allCases in debug'+allCases.size() );
        System.debug('getData'+caseList1.size());
        Integer i4 =[select count() from case where type='Repair'];
        Integer i5 =[select count() from case where type='Routine Maintenance'];
        Integer i6 =[select count() from case where type='Electrical'];
        System.debug('Test2-'+i4+'--'+i5+'---'+i6);
        System.assertEquals(300, i4);
        System.assertEquals(600, i5);
        System.assertEquals(0, i6);
          System.assertEquals(300, caseList1.size());    
           Test.stopTest();
    }
}



Main class:-

public without sharing class MaintenanceRequestHelper {
    //System.debug('main  ');
    public static void updateWorkOrders(Map<Id,Case>applicableCases) {
        // TODO: Complete the method to update workorders
        System.debug('*******Inside MaintenanceRequestHelper Class*******');
        Map<Id, Integer> mapProduct = new Map<Id, Integer>(); 
        List<Case> newCaseList = new List<Case>();
        List<Product2> listProduct = [select Id, Maintenance_Cycle__c from Product2];                                   
        for (Product2 p : listProduct) {
            if (p != null) {
                if(p.Maintenance_Cycle__c != null){
                    mapProduct.put(p.Id, Integer.valueOf(p.Maintenance_Cycle__c));
                }               
            }
        }
        for(Case a: applicableCases.values()){
            Case newCase = new Case();
            newCase.Vehicle__c = a.Vehicle__c;
            newCase.ProductId= a.ProductId;
            newCase.Type = 'Routine Maintenance';
            newCase.Subject = String.isBlank(a.Subject) ? 'Routine Maintenance Request' : a.Subject;
            newCase.Date_Reported__c = Date.today();
            newCase.Status = 'New';
            newCase.Product__c = a.Product__c;
            newCase.AccountId = a.AccountId;
            newCase.ContactId = a.ContactId;
            newCase.AssetId = a.AssetId;
            newCase.Origin = a.Origin;
            newCase.Reason = a.Reason;
            newCase.Date_Due__c =  (mapProduct.get(a.Id) != null) ? (Date.today().addDays(Integer.valueOf(mapProduct.get(a.Id)))) : (Date.today());
                newCaseList.add(newCase);
        }
        if(newCaseList.size() > 0){
            insert newCaseList;
        }    
    }        
}
My requirement is to display all the saved values on load for a Custom object called Company__c. Fields being Full_Name__c (text), Address__c(text area) , Director_Name__c (text), Phone__c (phone) and  Additional_Information__c(text). 

At present iteration is happening correctly and I can view inserted records via console.log in helper and system.debug in backend. However all the records getting displayed are empty with just one display button.

My Component code is as :- CompanyInfo.cmp

          <aura:component     implements="force:hasRecordId,           force:appHostable , flexipage:availableForRecordHome" 
                controller="CompanyController">
   <aura:registerevent name="forceNavig2Component"     type="force:navigateToComponent"/> 
    <aura:attribute name="Companies" type="Company__c"/>
    
        <!-- Handle component initialization in a client-side controller -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <!-- SHOW LOADING SPINNER--> 
    <lightning:spinner variant="brand" size="large"       aura:id="Id_spinner"   class="slds-hide" />

 <!-- Attribute declaration -->
    <aura:attribute name="companyObj" type="Company__c" default="    { 'sobjectType': 'Company__c' ,
                                                                 'Name':'',
                                                                 'Full_Name__c':'',
                                                                 'Director_Name__c':'',
                                                                 'Address__c':'',
                                                                 'Phone__c':''}"/>
    
    
    <div class="slds-grid">
        <lightning:card title="New Record" footer="Click on Save button     to create new Record.">
            <!-- Save button -->
            <aura:set attribute="actions">
                <lightning:button aura:id="saveId"
                                  label="Save"   
                                  onclick="{!c.doSave}"/>
            </aura:set>
            <!--/ Save button -->
            
            <!-- Body -->
            <p class="slds-p-horizontal_small">
                <lightning:input aura:id="CompanyName"
                                 label="Company Name"
                                 type="String"
                                 required="true"
                                 value="{!v.companyObj.Name}"/>
                <lightning:input aura:id="CompanyFullName"
                                 label="Full Name"
                                 type="String"
                                 required="true"
                                 value="{!v.companyObj.Full_Name__c}"/>
                    <lightning:input aura:id="CompanyDirector"
                                 label="Director Name"
                                 type="String"
                                     required="true"
                                 value="{!v.companyObj.Director_Name__c}"/>
                    <lightning:input aura:id="CompanyAddress"
                                 label="Address"
                                     required="true"
                                 type="String"
                                 value="{!v.companyObj.Address__c}"/>
                <lightning:input aura:id="CompanyPhone"
                                 label="Phone No"
                                 type="Number"
                                 required="true"
                                 value="{!v.companyObj.Phone__c}"/>
            </p>
            <!--/ Body -->
        </lightning:card>
        
         
     </div>
    
     <aura:iteration var="Company" items="{!v.Companies}">
                <!-- If you’re using a namespace, replace with                                       myNamespace:contacts-->
                <c:Companies Company="{!Company}"/>
            </aura:iteration>
 
      
     </aura:component>

Referred Component code for Companies.cmp is :-
       <aura:component>
         <aura:attribute name="Company" type="Company__c" />
    
        <lightning:card variant="Narrow" title="{!v.Company.Name}"                     iconName="standard:contact" >
            <aura:set attribute="actions">
                <lightning:button name="details" label="Details" onclick="              {!c.goToRecord}" />
            </aura:set>    
            <aura:set attribute="footer">
                <lightning:badge label="{!v.Company.Name}"/>
            </aura:set>
            <p class="slds-p-horizontal_small">
                {!v.Company.Name}
            </p>
            <p class="slds-p-horizontal_small">
                {!v.Company.Full_Name__c}
            </p>
              <p class="slds-p-horizontal_small">
                {!v.Company.Address__c}
            </p>
            <p class="slds-p-horizontal_small">
                {!v.Company.Director_Name__c}
            </p>
        </lightning:card>

         </aura:component>


Contoller code for main component is CompanyListController.js
    ({
    doInit : function(component, event, helper) {
        // Retrieve contacts during component initialization
        // 
        console.log("inside init function for loading companies")
        helper.loadCompanies(component,event, helper);
      },
      doSave : function(component, event, helper) {
    / ** Server side controller calling logic. **/
        
        //Calling server side controller's saveCompany() method.
        var action = component.get("c.saveCompany");
        //console.log(action);
        //
        //Set method parameter of saveCompany() method.
        action.setParams({"company":                                                                      component.get("v.companyObj")});
        
        action.setCallback(this, function(response){
            console.log('inside callback');
            //<response.getState()> return response status as                              SUCCESS/ERROR/INCOMPLETE etc.
            var state = response.getState();
            console.log("response state is"+ state);
            //If response from server side is <SUCCESS>, then we will                    display a success message.
            if (state === "SUCCESS"){
                //Success message display logic.
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Success!",
                    "message": "Company record has been inserted                               successfully."
                });
                toastEvent.fire();
            }else if (state === "INCOMPLETE") {
                //Offline message display logic.
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "OFFLINE!",
                    "message": "You are in offline."
                });
                toastEvent.fire();
            }else if (state === "ERROR") {
                //Error message display logic.
                var errors = response.getError();
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "ERROR!",
                    "message": errors[0].message
                });
                toastEvent.fire();
            }else {
                //Unknown message display logic.
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "UNKOWN!",
                    "message": "Unknown error."
                });
                toastEvent.fire();
            }
        });
        
        $A.enqueueAction(action);
        }
       })


Helper code is as follows:-

      ({
        loadCompanies : function(component,event, helper) {
         // show spinner message
         component.find("Id_spinner").set("v.class" , 'slds-show');
         // Load all contact data
         var action = component.get("c.getCompanies");
         action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                 // show spinner message
            component.find("Id_spinner").set("v.class" , 'slds-hide');
                var data = JSON.stringify(response.getReturnValue());
                console.log(data)
                component.set("v.Companies", data);
                console.log(component.get("v.Companies"));
                //var val = JSON.stringify(response.getReturnValue());
                //console.log("return value is "+val);
            }

            // Display toast message to indicate load status
            var toastEvent = $A.get("e.force:showToast");
            if (state === 'SUCCESS'){
                toastEvent.setParams({
                    "title": "Success!",
                    "message": " Your contacts have been loaded                                successfully."
                });
            }
            else {
                toastEvent.setParams({
                        "title": "Error!",
                        "message": " Something has gone wrong."
                });
            }
            toastEvent.fire();
        });
         $A.enqueueAction(action);
     }
          })



Apex class is as follows:-
      public with sharing class CompanyController {

       @AuraEnabled
      public static void saveCompany(Company__c company){
         INSERT company;
       }
    
    @AuraEnabled
    public static List<Company__c> getCompanies() {
        List<Company__c> companies = 
                [SELECT Name,       Full_Name__c, Address__c,                              Director_Name__c FROM Company__c];
     system.debug(companies);
        //Add isAccessible() check
        return companies;
    }
   }
hello,

i am a newbie to salesforce and trying to complete this trailhead challenge and unable to find a way through apex to generate this method for creating new contacts with unique id. as one requirement to pass the challenge is "The 'generateRandomContacts' method must be capable of consistently generating contacts with unique first names."

If somebody successfully completed the task kindly help me.

regards,