1

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");
      action.setCallback(this,function(response){
          component.set("v.account.OwnerId", response.getReturnValue().Id);
      });      
      $A.enqueueAction(action);
  },

and

init: function(component,event,helper) {

    this.getPicklistValues(component);
    this.loggedInAs(component,event,helper);
      alert(component.get("v.account.OwnerId"));

  }
1
<aura:component controller="ControllerName" 
            implements="flexipage:availableForAllPageTypes,forceCommunity:availableForAllPageTypes">    

<ltng:require styles="" 
              scripts=""
              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

    @AuraEnabled
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);
        helper.helperFunctionName(component);
    });
    $A.enqueueAction(action); 
}
  • You can call the action, from helper or from the JS... attributes are set the same way for both. – Logan Jun 23 '17 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 Jun 23 '17 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.