function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
hemanth tanguturi 10hemanth tanguturi 10 

Save and Load Records with a Server-Side Controller

Got Error  while implementing the lightning application for trailhead module "Connect to salesforce with server side controllers":
Error: Something has gone wrong. Error during init [TypeError: Cannot read property 'apply' of undefined] . Please try again.

Please help below is the Code, Pls help

CampingApp.app:
<aura:application >
	
    <ltng:require styles="{!$Resource.SLDS203 +
         '/assets/styles/salesforce-lightning-design-system.css'}"/>
    
    <div class="slds">
       
        <!-- This component is the real "app" -->
        <c:campingList />
       
    </div>
    
    
</aura:application>

CampingList.cmp:
<aura:component controller="CampingListController" >
    
    <aura:handler name="this" action="{!c.doInit}" value="{!this}"/>
    <aura:attribute name="newItem" type="Camping_Item__c"
                    default="{'sobjectType': 'Camping_Item__c',
                             'Price__c':0,
                             'quantity':0},
                             'Packed__c':false,
                             'Name':''}"/>
    <!--aura:attribute type="camping_item__c[]" name="items"/-->
        <aura:attribute name="items" type="Camping_Item__c[]"/>

    
    <!-- PAGE HEADER -->
    <div class="slds-page-header" role="banner">
      <div class="slds-grid">
        <div class="slds-col">
          <p class="slds-text-heading--label">Campings</p>
          <h1 class="slds-text-heading--medium">My Campings</h1>
        </div>
      </div>
    </div>
    <!-- / PAGE HEADER -->
    
    <!-- NEW Campign FORM -->
    <div class="slds-col slds-col--padded slds-p-top--large">


          
  <div aria-labelledby="CampingForm">

  <!-- BOXED AREA -->
  <fieldset class="slds-box slds-theme--default slds-container--small">

    <legend id="CampingForm" class="slds-text-heading--small 
      slds-p-vertical--medium">
      Add Camping
    </legend>

    <!-- CREATE NEW EXPENSE FORM -->
    <form class="slds-form--stacked">

      <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="campingName" label="Camping Name"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newItem.Name}"
                  required="true"/>
          </div>
     </div>

     <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputNumber aura:id="Price" label="Price"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newItem.Price__c}"
                  required="true"/>

          </div>
      </div>

      
      <div class="slds-form-element">
          <div class="slds-form-element__control">
              <ui:inputNumber aura:id="quantity" label="Quantity"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newItem.Quantity__c}"
                  required="true"/>
          </div>
      </div>

      <div class="slds-form-element">
          <ui:inputCheckbox aura:id="packed" label="Packed?"
              class="slds-checkbox"
              labelClass="slds-form-element__label"
              value="{!v.newItem.Packed__c}"/>
      </div>

      <div class="slds-form-element">
          <ui:button label="Create Campign"
              class="slds-button slds-button--brand"
              press="{!c.clickCreateCamping}"/>
      </div>

    </form>
    <!-- / CREATE NEW EXPENSE FORM -->

  </fieldset>
  <!-- / BOXED AREA -->

</div>
        </div>
    
    
    
    <div class="slds-col slds-col--padded slds-p-top--large">
    <aura:iteration items="{!v.items}" var="item">
      <c:campingListItem item="{!item}"/>
        </aura:iteration>
    </div>
    
    
    
</aura:component>

CampingListController.js:
({
    
    // Load expenses from Salesforce
doInit: function(component, event, helper) {

    // Create the action
    var action = component.get("c.getItems");

    // Add callback behavior for when response is received
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (component.isValid() && state == "SUCCESS") {
            console.log("Result: " + response.getReturnValue());
            component.set("v.items", response.getReturnValue());
        }
        else {
            console.log("Failed with state: " + state);
        }
    });

    // Send action off to be executed
    $A.enqueueAction(action);
},
    
    
    
    clickCreateCamping: function(component, event, helper) {

        // Simplistic error checking
        var validCamping = true;

        // Name must not be blank
        var nameField = component.find("campingName");
        var campname = nameField.get("v.value");
        
        if ($A.util.isEmpty(campname)){
            validCamping = false;
            nameField.set("v.errors", [{message:"Camping name can't be blank."}]);
        }
        else {
            nameField.set("v.errors", null);
        }
        
        if ($A.util.isEmpty(component.find("quantity").get("v.value"))){
            validCamping = false;
            component.find("quantity").set("v.errors", [{message:"Camping Quantity can't be blank."}]);
        }
        else {
            component.find("quantity").set("v.errors", null);
        }
        if ($A.util.isEmpty(component.find("Price").get("v.value"))){
            validCamping = false;
            component.find("Price").set("v.errors", [{message:"Camping Price can't be blank."}]);
        }
        else {
            component.find("Price").set("v.errors", null);
        }
        
        

        // ... hint: more error checking here ...

        // If we pass error checking, do some real work
        if(validCamping){
            // Create the new expense
            
            var newCampignItem = Component.get("v.newItem");
            helper.createItem(component, newCampignItem);
        }
    }
})

CampingListController.aspx:
public class CampingListController {

    @auraEnabled
    Public static list<Camping_Item__c> getItems(){
        
        return [select Name, Quantity__c, Price__c, Packed__c from Camping_Item__c];
        
    }
    
    @auraEnabled
    Public static Camping_Item__c saveItem (Camping_Item__c Camping){
        
        upsert Camping;
        return Camping;
        
    }
    
}

CampingListHelper:
({
	createItem : function(component, campingItem) {
		var action = component.get("c.saveItem");
        action.setParams({"Camping", campignItem});
                          
                          action.setCallback(this, function(response){
                          var state = response.getState();
        				if (component.isValid() && state === "SUCCESS") {
            				var items = component.get("v.Items");
            				expenses.push(response.getReturnValue());
            				component.set("v.Items", items);
                         }
                         });
                          $A.enqueueAction(action);
        
	}
})



 
SandhyaSandhya (Salesforce Developers) 
Hi,

Below is the working code.


CampingList.js​
 
({
	
    doInit  : function(component, event, helper) {
		var action = component.get("c.getItems");
        action.setCallback(this, function(response){
            var state = response.getState();
           
            if (component.isValid() && state === "SUCCESS") {
           
               
                component.set("v.items", response.getReturnValue());
                 
            }
        });
        
        $A.enqueueAction(action);
	},
    
    CreateCamping : function(component, event, helper){
        
        helper.validateFields (component,component.find("name"));
        helper.validateFields (component,component.find("Price"));
        helper.validateFields (component,component.find("Quantity"));
        if(component.get("v.er") === false)
        {     
&nbsp;           //Here I removed the lines and shifted the code to the helperJs       
            console.log('Before:'+Items);            
            helper.CreateCampaign(component,Item);             
             console.log('After:'+Items);                    
        }
	}    
})
CampingListHelper.js
 
({
	
    validateFields : function (component,field) {
        
        var nameField = field;
        console.log('yes:'+nameField);
        var expname = nameField.get("v.value"); 
        if ($A.util.isEmpty(expname)){
           component.set("v.er",true);
           nameField.set("v.errors", [{message:"this field can't be blank."}]);
        }
        else {
            nameField.set("v.errors", null);
        }
    },
    
    CreateCampaign : function (component,Item){ 
		    
        var action = component.get("c.saveItem");
        action.setParams({"CampingItem":Item});
        action.setCallback(this,function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                console.log('save');
            }
        });
        $A.enqueueAction(action);  
//Below lines are shifted from controller Js to helperJs
        var Items = component.get("v.items"); 
&nbsp;       var Item = component.get("v.newItem"); 
&nbsp;       Items.push(Item);    
        component.set("v.items",Items); 
        component.set("v.newItem",{ 'sobjectType': 'Camping_Item__c',
                'Name': '',
                'Quantity__c': 0,
                'Price__c': 0,
                'Packed__c': false });
    }
})

campingListItem.js​
({
	    
    packItem : function(component, event, helper) {
		var pack = component.get("v.item");
        pack.Packed__c = true;
        component.set("v.item",pack);
        var btnClicked = event.getSource();
        btnClicked.set("v.disabled",true);
        
	}
    
    
})

campingListItem.cmp
 
<aura:component >
    
   
    <aura:attribute type="Camping_Item__c" name="item" required="true"/>
    Name:
    <ui:outputText value="{!v.item.Name}" /><br/>
    Packed:
    <ui:outputCheckbox value="{!v.item.Packed__c}" /><br/>
    Price:
    <ui:outputCurrency value="{!v.item.Price__c}" /><br/>
   
    Quantity:
     <ui:outputNumber value="{!v.item.Quantity__c}" /><br/>
    
    <ui:button label="Packed!"  press="{!c.packItem}" aura:id = "Button"/> <br/>
</aura:component>
 
public class CampingListController {
&nbsp;&nbsp; &nbsp;@auraenabled
&nbsp; &nbsp; public static List<Camping_Item__c> getItems (){
&nbsp; &nbsp; &nbsp; &nbsp; List<Camping_Item__c> CI = [select id, name,price__c,Quantity__c,Packed__c from Camping_Item__c ];
&nbsp; &nbsp; &nbsp; &nbsp; return CI;
&nbsp; &nbsp; }
&nbsp; &nbsp; @auraenabled
&nbsp; &nbsp; public static Camping_Item__c saveItem (Camping_Item__c CampingItem){
&nbsp; &nbsp; &nbsp; &nbsp; insert campingItem;
&nbsp; &nbsp; &nbsp; &nbsp; return campingItem;
&nbsp; &nbsp; }
}
 
<aura:component controller="CampingListController">
    <aura:handler name = "init" value="{!this}" action = "{!c.doInit}"/>
	<aura:attribute name="items" type="Camping_Item__c[]"/>
    <aura:attribute name="er" type="boolean" default="false"/>
    <aura:attribute name="newItem" type="Camping_Item__c"    default="{ 'sobjectType': 'Camping_Item__c',
                         'Name': '',
                         'Price__c': 0,
                         'Quantity__c': 0,                         
                         'Packed__c': false
                       }"/>
    <ui:inputText value="{!v.newItem.Name}" aura:id="name" label="name"/>
    <ui:inputCheckbox value="{!v.newItem.Packed__c}" aura:id="Packed" label="Packed"/>
    <ui:inputCurrency value="{!v.newItem.Price__c}"  aura:id="Price" label="Price"/>
    <ui:inputNumber value="{!v.newItem.Quantity__c}" aura:id="Quantity" label="Quantity"/>
    <ui:button label="Create Expense" press="{!c.CreateCamping}" aura:id="button"/>
    <br/>
	<aura:iteration items="{!v.items}" var="PerItem">
        
        <c:campingListItem item="{!PerItem}" />
    </aura:iteration>
</aura:component>

Hope this helps you!

Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
 
Thanks and Regards
Sandhya


 
Stephen Stanley 2Stephen Stanley 2
A few minor corrections to @sandya's solution:

1. The 5th block of code needs to pasted into a new Apex Class named CampingListController
2. The 6th Block of code needs to be pasted into your CampingList.cmp file
3. The helper code (2nd Block of code) has a reference to CreateCampaign, this should be renamed "createItem" 
4. The controller code CampingListController.js (refedrred to as CampingList.js in the first block of code needs to call "createItem" in the helper, not "CreateCampaign"