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
Christoph Hallmann 4Christoph Hallmann 4 

connect to salesforce with server-side controller - challenge gets not accepted

I have some issues with the following trail


Lightning Components Basics > Connect to Salesforce with Server-Side Controllers

the error message I'm receiving

Challenge not yet complete... here's what's wrong:
The campingList JavaScript helper doesn't appear to have the correct functionality. Ensure that it is saving the new record to the database and in the callback, pushing the new record to the array of existing items (e.g., v.items) and setting the modified array of items to the 'items' value provider to display the updated list.


here is my code

CampingListController.apxc

 

public class CampingListController {    
    
    @AuraEnabled
    public static List<Camping_Item__c> getItems() {
        System.debug('Called get Items');
        List<Camping_Item__c> campingItems = [SELECT Name, Price__c, Quantity__c, Packed__c FROM Camping_Item__c];
        return campingItems;
    }
    
    @AuraEnabled
    public static Camping_Item__c saveItem(Camping_Item__c item) {
        try{
            upsert item;
            System.debug('success');
        } catch (Exception e) {
           System.debug('error found'); 
        }
        
        return item;
        
    }
}
campingListController.js
 
({
	clickCreateItem : function(component, event, helper) {
        var validListItem = component.find('itemform').reduce(function(validSoFar, inputCmp){
            inputCmp.showHelpMessageIfInvalid();
            return validSoFar && inputCmp.get('v.validity').valid;
        }, true);	
        
        if (validListItem) {
            var currentItem = component.get("v.newItem");
            var newItem = JSON.parse(JSON.stringify(currentItem));
            var action = component.get("c.saveItem");  
            helper.createItem(newItem, action, component);
           
        }
	},
    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) {
            console.log("callback");
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.items", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        // Send action off to be executed
        $A.enqueueAction(action);
	}
})

campingListHelper.js
 
({
	createItem : function(item, action, component) {
        var items = component.get("v.items");
        
        action.setParams({
            "item" : item
        });

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                
                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 });
            }
        });
            
        $A.enqueueAction(action);

	}
})

campingList.cmp
 
<aura:component controller="CampingListController">
     
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <aura:attribute name="newItem" type="Camping_Item__c"
         default="{ 'sobjectType': 'Camping_Item__c',
                        'Name': '',
                        'Price__c': 0,
                        'Quantity__c': 0,
                        'Packed__c': false }"/>
    <aura:attribute name="items" type="Camping_Item__c[]"/>
    <div>
    	<fieldset class="slds-box slds-theme--defaul slds-container--small">
            <legend id="newitemform" class="slds-text-heading--small 
              slds-p-vertical--medium">
              Add Item entry
            </legend>
            
            
            <form class="slds-form--stacked">         
                <lightning:input aura:id="itemform" label="Item Name"
                             name="itemname"
                             value="{!v.newItem.Name}"
                             required="true"/>
                 
                <lightning:input type="number" aura:id="itemform" label="Price"
                                 name="Price"
                                 formatter="currency"
                                 value="{!v.newItem.Price__c}" />
                
                <lightning:input type="number" aura:id="itemform" label="Quantity"
                                 name="Quantity"
                                 min="1"
                                 messageWhenRangeUnderflow="Enter an amount that works"
                                 value="{!v.newItem.Quantity__c}" />
                
                 <lightning:input type="checkbox" aura:id="itemform" label="Packed"  
                             name="Packed"
                             checked="{!v.newItem.Packed__c}"
                             value="{!v.newItem.Packed__c}" />
                
                <lightning:button label="Create List Entry" 
                              class="slds-m-top--medium"
                              variant="brand"
                              onclick="{!c.clickCreateItem}"/>
                
            </form>
            
            
        </fieldset>
        
        
        <lightning:card title="List Items">
           <p class="slds-p-horizontal--small">
                <aura:iteration items="{!v.items}" var="item">
                    <c:campingListItem item="{!item}"/><br/>
                </aura:iteration>
            </p>
        </lightning:card>
    </div>
    
</aura:component>

When I hit preview in my component everything works but I cannot figure out what to do to complete the challenge.
For me it seems it should pass through.

thanks for help​
 
Best Answer chosen by Christoph Hallmann 4
Raj VakatiRaj Vakati
try this code
 
public class CampingListController {
    @auraenabled
    public static List<Camping_Item__c> getItems (){
        List<Camping_Item__c> CI = [select id, name,price__c,Quantity__c,Packed__c from Camping_Item__c ];
        return CI;
    }
    @auraenabled
    public static Camping_Item__c saveItem (Camping_Item__c item){
        insert item;
        return item;
    }
}
 
<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 Camping" press="{!c.createItem}" aura:id="button"/>
    <br/>
	<aura:iteration items="{!v.items}" var="PerItem">
        
        <c:campingListItem item="{!PerItem}" />
    </aura:iteration>
</aura:component>
 
({
	
    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);
	},
    
    createItem : 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)
        {     
            var Item = component.get("v.newItem");            
            helper.createItem (component,Item);             
                       
        }
	}    
})
 
({
	
    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);
        }
    },
    
    createItem : function (component,Item){         
        var action = component.get("c.saveItem");
        action.setParams({"item":Item});
        action.setCallback(this,function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var campings = component.get("v.items");
                campings.push(response.getReturnValue());
                component.set("v.items", campings);
            }
        });
       $A.enqueueAction(action);        
    }
})

 

All Answers

Raj VakatiRaj Vakati
try this code
 
public class CampingListController {
    @auraenabled
    public static List<Camping_Item__c> getItems (){
        List<Camping_Item__c> CI = [select id, name,price__c,Quantity__c,Packed__c from Camping_Item__c ];
        return CI;
    }
    @auraenabled
    public static Camping_Item__c saveItem (Camping_Item__c item){
        insert item;
        return item;
    }
}
 
<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 Camping" press="{!c.createItem}" aura:id="button"/>
    <br/>
	<aura:iteration items="{!v.items}" var="PerItem">
        
        <c:campingListItem item="{!PerItem}" />
    </aura:iteration>
</aura:component>
 
({
	
    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);
	},
    
    createItem : 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)
        {     
            var Item = component.get("v.newItem");            
            helper.createItem (component,Item);             
                       
        }
	}    
})
 
({
	
    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);
        }
    },
    
    createItem : function (component,Item){         
        var action = component.get("c.saveItem");
        action.setParams({"item":Item});
        action.setCallback(this,function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var campings = component.get("v.items");
                campings.push(response.getReturnValue());
                component.set("v.items", campings);
            }
        });
       $A.enqueueAction(action);        
    }
})

 
This was selected as the best answer
Christoph Hallmann 4Christoph Hallmann 4
but what is wrong with my version?