[SalesForce] How to get value from client-side to server-side from lightning component

I am experimenting with the example of Trailhead AccountList lightning components. The part to get server-side to client-side works.

I am trying to pass a value from client-side to server-side but this doesn't give me a value.

AccountlistController.js

 ({
  doInit: function(component, event, helper) {      
    // Fetch the account list from the Apex controller   
    helper.getAccountList(component);
  },
  IdAccount: function(component, event, helper) {
    // Prevent the form from getting submitted
    event.preventDefault();

    // Get the value from the field that's in the form
    var accountName = event.target.getElementsByClassName('account-name')[0].value;
    var accountId = event.target.getElementsByClassName('account-id')[0].value;

    confirm('Set the id '+ accountId +'For '+ accountName + ' account? ');

      var action = component.get("c.ServerAccountEcho");
      action.setParams({  recordId : accountId  });// setting the parameter to apex class method
  }
})

AccountsController

 public class AccountsController {
  @AuraEnabled
  public static List<Account> getAccounts() {
    return [SELECT id,Name FROM Account];
  }


  public static void ServerAccountEcho(id recordId) {
 system.debug('recordId ' + recordId);
 List<User>  U = [Select id,Name, CurrentAccountIdComm__c FROM User WHERE Firstname='Alex'];
      U[0].CurrentAccountIdComm__c = 'echo';
      update U;
}  

}

Component

  <aura:component controller="AccountsController" implements="flexipage:availableForRecordHome" access="global">  

    <aura:attribute name="accounts" type="List" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <!--
    Use a data table from the Lightning Design System:
    https://www.lightningdesignsystem.com/components/data-tables/
  -->
    <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
        <thead>
            <tr class="slds-text-heading--label">
                <th scope="col"><div class="slds-truncate" title="ID">ID</div></th>
                <th scope="col"><div class="slds-truncate" title="Name">Name</div></th>
            </tr>
        </thead>
        <tbody>
            <!-- Use the Apex model and controller to fetch server side data -->
            <aura:iteration items="{!v.accounts}" var="account">
                <tr>
                    <th scope="row"><div class="slds-truncate" title="{!account.Id}">{!account.Id}</div></th>
                    <td><div class="slds-truncate" title="{!account.Name}">{!account.Name}</div></td>
                    <td>
                        <form class="account-form" onsubmit="{!c.IdAccount}">
                            <input type="hidden" value="{!account.Name}" class="account-name" />
                            <input type="hidden" value="{!account.Id}" class="account-id" />


                            <lightning:button iconName="utility:forward"
                                              iconPosition="left"
                                              variant="neutral"
                                              type="submit"
                                              />

                        </form>
                    </td>
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>

Best Answer

I'm assuming you are successfully calling the JS Controller's IdAccount() function from somewhere. If that is the case, then you are not successfully calling your server side method because you did not add the server side action to the queue.

Here's some sample code which shows you the correct way to call a method from your server side controller:

({
    "echo" : function(cmp) {
        // create a one-time use instance of the serverEcho action
        // in the server-side controller
        var action = cmp.get("c.serverEcho");
        action.setParams({ firstName : cmp.get("v.firstName") });

        // Create a callback that is executed after 
        // the server-side action returns
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                // Alert the user with the value returned 
                // from the server
                alert("From server: " + response.getReturnValue());

                // You would typically fire a event here to trigger 
                // client-side notification that the server-side 
                // action is complete
            }
            else if (state === "INCOMPLETE") {
                // do something
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });

        // optionally set storable, abortable, background flag here

        // A client-side action could cause multiple events, 
        // which could trigger other events and 
        // other server-side action calls.
        // $A.enqueueAction adds the server-side action to the queue.
        $A.enqueueAction(action);
    }
})

Notice the 3 main steps:

  1. Create instance of server side action: var action = cmp.get("c.serverEcho");
  2. Create a callback that is executed after server side action returns: action.setCallback(this, function(response) {...
  3. Add the server side action to the queue to be executed: $A.enqueueAction(action);

You can find more information (along with the example above) here: Calling Server-Side Actions

Related Topic