How do I set value from init on attribute in lightning component? helper method:

loggedInAs: function(component,event,helper){
    var action = component.get("c.getCurrentUser");
          component.set("v.account.OwnerId", response.getReturnValue().Id);


init: function(component,event,helper) {



1 Answer 1

<aura:component controller="ControllerName" 

<ltng:require styles="" 
              afterScriptsLoaded="{!c.loggedInAs}" />

<aura:attribute name="getObject" type="sobject[]" />
<aura:attribute name="fieldValue1" type="String" />
<aura:attribute name="fieldValue2" type="String" />

If you don't run scripts, and just want to use a handler, it would look like this, but with the name of the JS function you want to fire.

    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

Your Controller

public static List<ObjectName__c> getInfo(){

    List<User> usr = [SELECT Id, ContactID FROM User WHERE Id = : UserInfo.getUserId()];
    List<Contact> cont =  [SELECT Id, LookupFieldToObject__c FROM Contact WHERE Id = : usr.get(0).ContactID limit 1];

        return [SELECT Id, Name
            FROM ObjectName__c
            WHERE Id = : cont.get(0).LookupFieldToObject__c
            Limit 1

Then, your JS

loggedInAs: function(component,event,helper){

    var action = component.get("c.getInfo"); 
    action.setCallback(this, function(response) {
        var theResult = response.getReturnValue();

        component.set("v.getObject", theResult);
        component.set("v.fieldValue1", theResult[0].Id);
        component.set("v.fieldValue2", theResult[0].Name);
  • You can call the action, from helper or from the JS... attributes are set the same way for both.
    – Logan
    Commented Jun 23, 2017 at 15:45
  • note that the helper function call is inside the action and not after the '$A.enqueueAction(action); '. This is because you want the helper function to fire after your attributes are set and not before. Remember that it takes time for the apex information to be called, and if you don't put the helper inside, it will probably fire your helper function before you have your attributes set.
    – Logan
    Commented Jun 23, 2017 at 15:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .