Monday, 20 November 2017

Lightning Components Basics: Connect to Salesforce with Server Side Controllers

Lightning Components Basics: Connect to Salesforce with Server Side Controllers

Campaign List Component Code


<aura:component controller="CampingListController"
implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
<aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    

    <aura:attribute name="items" type="Camping_Item__c[]"/>
    <aura:attribute name="newItem" type="Camping_Item__c" default="{ 'sobjectType': 'Camping_Item__c',
                        'Name': '',
                        'Quantity__c': 0,                                          
                        'Price__c': 0,
                        'Packed__c': false }"/>
    <!--<ol>
        <li>Bug Spray</li>
        <li>Bear Repellant</li>
        <li>Goat Food</li>
    </ol>  -->
    <!-- PAGE HEADER -->
    
    <c:campingHeader />

    <lightning:layout >
        <lightning:layoutItem padding="around-small" size="6">
<div aria-labelledby="newcampaignform">
                <fieldset class="slds-box slds-theme--default slds-container--small">
    <legend id="newcampaignform" class="slds-text-heading--small slds-p-vertical--medium">
                    Add Campaign List
                    </legend> 
                    <form class="slds-form--stacked">
                        <lightning:input aura:id="campaignform" label="Campaign Item Name"
                         name="campaignitemname"
                         value="{!v.newItem.Name}"
                         required="true"/>
                        <lightning:input type="number" aura:id="expenseform" label="Quantity"
                         name="campaignitemprice"
                         min="1"
                         formatter="number"
                         step="0.1"
                         value="{!v.newItem.Quantity__c}"
                         messageWhenRangeUnderflow="Enter quantity that's at least 1."/>
<lightning:input type="number" aura:id="expenseform" label="Price"
                         name="campaignitemprice"
                         min="0.1"
                         formatter="currency"
                         step="0.01"
                         value="{!v.newItem.Price__c}"
                         messageWhenRangeUnderflow="Enter an amount that's at least $0.10."/>
<lightning:input type="checkbox" aura:id="expenseform" label="Packed?" 
                         name="expreimbursed"
                         checked="{!v.newItem.Packed__c}"/>
<lightning:button label="Create Camping" class="slds-m-top--medium"
                                 variant="brand" onclick="{!c.clickCreateItem}"/>
                    </form>
                </fieldset>
            </div>
            
</lightning:layoutItem>
    </lightning:layout>
    <c:campingHeader />

<div class="slds-card slds-p-top--medium">
        <header class="slds-card__header">
            <h3 class="slds-text-heading--small">Items</h3>
        </header>
         
        <section class="slds-card__body">
            <div id="list" class="row">
                <aura:iteration items="{!v.items}" var="items">
                    <c:campingListItem item="{!item}"/>
                </aura:iteration>
            </div>
        </section>
    </div>

</aura:component>


CampaignListController Code


({
     // 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 (state === "SUCCESS") {
                component.set("v.items", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
    
        // Send action off to be executed
        $A.enqueueAction(action);
    },
    
clickCreateItem: function(component, event, helper) {
        var validCamping = component.find('campingform').reduce(function (validSoFar, inputCmp) {
            // Displays error messages for invalid fields
            inputCmp.showHelpMessageIfInvalid();
            return validSoFar && inputCmp.get('v.validity').valid;
        }, true);
if(validCamping){
var addItm = event.getParam("item");
            helper.createItem(component, addItm);
            var newCampingItem = component.get("v.newItem");
            var campings = component.get("v.items");
            var item = JSON.parse(JSON.stringify(newCampingItem));
            campings.push(item);
            component.set("v.items",campings);
            component.set("v.newItem",{ 'sobjectType': 'Camping_Item__c','Name': '','Quantity__c': 0,
                                           'Price__c': 0,'Packed__c': false });
        }


}
})

Campaign  List Helper Code

({
   
    createItem : function(component, campaign) {
        var action = component.get("c.saveItem");
        action.setParams({
            "item": campaign
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var expenses = component.get("v.items");
                expenses.push(response.getReturnValue());
                component.set("v.items", expenses);
            }
        });
        $A.enqueueAction(action);
    },
})

17 comments:

  1. Challenge Not yet complete... here's what's wrong:
    The Apex controller CampingListController doesn't have a 'getItems()' or 'saveItem(Camping_Item__c item)' method.

    ReplyDelete
  2. Nice blog!! thank you.
    Here is the missed class code:

    public class CampingListController {
    @auraenabled
    public static List getItems (){
    List 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 CampingItem){
    insert campingItem;
    return campingItem;
    }
    }

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. You're missing the List type in your getItems() method. Make sure to use List < Camping_Item__c > in both places in that method instead of just declaring List by itself.

      After trying to comment several times, I realized the site is automatically removing what's in between the < and > unless I put spaces like above. Hope that helps anyone reading this.

      Delete
  3. Thanks for pasting the code! It helped me troubleshoot my challenge!

    ReplyDelete
  4. Great Post. The information provided is of great use as I got to learn new things. Keep Blogging.Dell Boomi Training in Bangalore



    ReplyDelete
  5. Hi All,

    I am still gettingThe Apex controller CampingListController doesn't have a 'getItems()' or 'saveItem(Camping_Item__c item)' method. error.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. public class CampingListController {
    @auraenabled
    public static List getItems (){
    List CI = [select id, name,price__c,Quantity__c,Packed__c from Camping_Item__c ];
    return CI;
    }
    @auraenabled
    public static List saveItem (Camping_Item__c CampingItem){
    insert campingItem;
    return campingItem;
    }
    }

    ReplyDelete
  8. Just found your post by searching on the Google, I am Impressed and Learned Lot of new thing from your post.
    Dell Boomi training in bangalore

    ReplyDelete