[SalesForce] Aura:Iteration Tag Not Working

I am trying to display information from the users object, but I cannot get the components to cooperate. Code is below:

apex:

public with sharing class LACC_ObjController {
  @AuraEnabled
  public static List<User> getMyObjects() {
    return [SELECT Id, Name FROM User];
  }
}

cmp:

<aura:component controller="LACC_ObjController">
  <aura:attribute name="MyObjects" type="User[]" />
  <aura:iteration items="{!v.MyObjects}" var="obj">
            {!obj.Id}
  </aura:iteration>
</aura:component>

and js:

({
  getMyObjects: function(cmp){
    var action = cmp.get("c.getMyObjects");
    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === "SUCCESS") {
            cmp.set("v.myObjects", response.getReturnValue());
        }
    });
    $A.enqueueAction(action);
  }
})

The when I view the page, nothing shows up. Any suggestions?

Best Answer

You need to call the DoInit handler. Rename your javascript from "getMyObjects" to "doInit."

Component:

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

Controller:

({
  doInit: function(cmp){
    var action = cmp.get("c.getMyObjects");
    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === "SUCCESS") {
            cmp.set("v.MyObjects", response.getReturnValue());
        }
    });
    $A.enqueueAction(action);
  }
})

As a best practice, you should not name your client side functions the same as your apex controller. If you do, you could end up recursively calling the controller which will throw a big error.

Please also note that javascript is case sensitive. Your set of "MyObjects" was spelled as "myObjects" and would have thrown an error.

Related Topic