[SalesForce] Should all AuraEnabled methods be static

I was working on the apex controller of my first Lightning Component today, when I got an strange error message:

AuraEnabled methods must be named with a prefix 'get'

I noticed that all of the examples from the developers' guide used static methods, and often didn't start with 'get'.

When I made my method static in the controller, sure enough, the error message went away even though the method name still doesn't start with 'get'.

So, my question is, do you think the compiler was trying to warn me that the method wasn't static, and is there a reason for making all server-side methods in lightning components static?

Best Answer

It turns out that AuraEnabled methods need to be static. On page 19 of the guide (in the quick start section), it says:

@AuraEnabled enables client- and server-side access to the controller method. Server-side controllers must be static and all instances of a given component share one static controller.

It would have been nice if this was also in server-side controller overview part of the guide, or if the compiler had given a more descriptive error message.

I was able to get the controller to compile with a non-static method, but it ended up producing an error when attempting to access the method. Setting the method to static resolved the issue.

// app

<aura:application >
    <c:TestComponent />
</aura:application>

// component, named TestComponent

<aura:component controller="LightningController">
    <aura:attribute name="NewAccountId" type="String" default="The id goes here."/>
    <ui:button label="Push me" press="c.handlePress" />
        <ui:outputText value="{!v.NewAccountId}" />
</aura:component>

// client-side controller

({
    handlePress : function(component, event, helper) {
        var action = component.get("c.getInsertAccount");
        action.setCallback(this,function(response){
                if (response.getState() === "SUCCESS"){
                    component.set("v.NewAccountId",response.getReturnValue());
                }
            });
        $A.enqueueAction(action);
    }
})

// server-side controller

public class LightningController {

    @AuraEnabled
    public Id getInsertAccount(){
        Account a = new Account(Name = 'I\'m new here');
        insert a;
        return a.Id;
    }

}

// The error

An internal server error has occurred

Error ID: 1460235107-175036 (-852516609)