Search code examples
salesforceapexsalesforce-lightningaura-framework

Display value as returned from controller method


Beginner in Salesforce so please bear with me. I have created a lightning component and I would like to display on a page a value as returned by a component controller.

public class My_Controller { 
@AuraEnabled
public static Decimal getRate(String currFrom, String currTo) {

Decimal value = 1.067773;

return value;  
}
}

<aura:component controller="My_Controller">

<lightning:input type="string" name="res" aura:id="res" value= " 
{!c.My_Controller.getRate('A', 'B')}" label="Result"/>

But it could not be so simple :) as I get: "Failed to save Rate.cmp: unexpected token: '(' at column 46 of expression: c.My_Controller.getRate('A', 'B'): Source"

What is the proper way to call the method?


Solution

  • You cannot call an Apex server controller method directly from Lightning clientside markup.

    Instead, you'd need to declare an <aura:attribute> in your component markup and bind the value to that attribute.

    <aura:attribute name="rate" type="String" />
    <lightning:input type="string" name="res" aura:id="res" value="{! v.rate }" label="Result"/>
    

    Then, your JavaScript client-side controller needs to make a server-side call, asynchronously, to get the value from Apex. Finally, the Lightning JavaScript callback from that async method would populate the return value into the <aura:attribute>, and the framework's data binding infrastructure will take care of updating the <lightning:input>.

    It sounds complex, but it's mostly boilerplate code. The documentation linked above includes detailed examples.