Monday, February 13, 2017

What are Server-Side Controllers in lightning components and how to use server-side controllers?.

What are Server-Side Controllers in lightning components and how to use server-side controllers?.


Server-Side Controller
Create a server-side controller in Apex and use the @AuraEnabled annotation to enable client- and server-side access to the controller method.
Only methods that you have explicitly annotated with @AuraEnabled are exposed. Calling server-side actions aren’t counted against your org’s API limits. However, your server-side controller actions are written in Apex, and as such are subject to all the usual Apex limits.
This Apex controller contains a serverEcho action that prepends a string to the value passed in.
public with sharing class SimpleServerSideController {

    //Use @AuraEnabled to enable client- and server-side access to the method
    @AuraEnabled
    public static String serverEcho(String firstName) {
        return ('Hello from the server, ' + firstName);
    }
}


In addition to using the @AuraEnabled annotation, your Apex controller must follow these requirements.
  •     Methods must be static and marked public or global. Non-static methods aren’t supported.
  •     If a method returns an object, instance methods that retrieve the value of the object’s instance field must be public.


Creating an Apex Server-Side Controller
Use the Developer Console to create an Apex server-side controller.
1.      Open the Developer Console.
2.      Click File | New | Apex Class.
3.      Enter a name for your server-side controller.
4.      Click OK.
5.    Enter a method for each server-side action in the body of the class. 
6.    Click File | Save
7.    Open the component that you want to wire to the new controller class. 
8.    Add a controller system attribute to the <aura:component> tag to wire the 
   component to the controller. For example:


<aura:component controller="SimpleServerSideController" >


Returning Errors from an Apex Server-Side Controller


Create and throw a System.AuraHandledException from your server-side controller to return a custom error message.

Errors happen. Sometimes they’re expected, such as invalid input from a user, or a duplicate record in a database. Sometimes they’re unexpected, such as... Well, if you’ve been programming for any length of time, you know that the range of unexpected errors is nearly infinite.

When your server-side controller code experiences an error, two things can happen. You can catch it there and handle it in Apex. Otherwise, the error is passed back in the controller’s response.

If you handle the error Apex, you again have two ways you can go. You can process the error, perhaps recovering from it, and return a normal response to the client. Or, you can create and throw an AuraHandledException.

The benefit of throwing AuraHandledException, instead of letting a system exception be returned, is that you have a chance to handle the exception more gracefully in your client code. System exceptions have important details stripped out for security purposes, and result in the dreaded “An internal server error has occurred…” message. Nobody likes that. When you use an AuraHandledException you have an opportunity to add some detail back into the response returned to your client-side code. More importantly, you can choose a better message to show your users.

Here’s an example of creating and throwing an AuraHandledException in response to bad input. However, the real benefit of using AuraHandledException comes when you use it in response to a system exception. For example, throw an AuraHandledException in response to catching a DML exception, instead of allowing that to propagate down to your client component code.


public with sharing class SimpleErrorController {     static final List<String> BAD_WORDS = new List<String> {        'bad',        'words',        'here'    }; 
    @AuraEnabled    public static String helloOrThrowAnError(String name) {         // Make sure we're not seeing something naughty        for(String badWordStem : BAD_WORDS) {            if(name.containsIgnoreCase(badWordStem)) {                // How rude! Gracefully return an error...                throw new AuraHandledException('NSFW name detected.');            }        }     
        // No bad word found, so...        return ('Hello ' + name + '!');    } 
}



Calling a Server-Side Action

Call a server-side controller action from a client-side controller. In the client-side controller, you set a callback, which is called after the server-side action is completed. A server-side action can return any object containing serializable JSON data. A client-side controller is a JavaScript object in object-literal notation containing name-value pairs. Each name corresponds to a client-side action. Its value is the function code associated with the action Let’s say that you want to trigger a server-call from a component. The following component contains a button that’s wired to a client-side controller echo action. ServerSideLightningController contains a method that returns a string passed in from the client-side controller.
Example : Component

 Controller

Output : 


for reference  :

26 comments:

Nbits said...

thank you for sharing such a good and useful information, please keep on share like this
salesforce training in hyderabad
salesforce online training

radha said...

Nice post.Keep sharing salesforce Online Training Hyderabad

Aishwarya said...

This is an awesome post. Really very informative and creative. This sharing concept is a good way to enhance the knowledge. Thank you very much for this post. I like this site very much. I like it and it help me to development very well...
Mobile App Development Company In Chennai
Android App Development Company In Chennai
Android Application Development Company In Chennai
Custom Web Application Development Company In Chennai

Dharani M said...

Awesome article

salesforce training in Marathahalli

salesforce admin training in Marathahalli

salesforce developer training in Marathahalli

mounika said...

Nice post.

salesforce training in btm

salesforce admin training in btm

salesforce developer training in btm

kirankumar said...

Good blog information
Best Play and Pre School for kids in Hyderabad,India. To give your kid a best environment and learning it is the right way to join in play and pre school were kids can build there physically, emotionally and mentally skills developed. We provide programs to kids like Play Group, Nursery, Sanjary Junior, Sanjary Senior and Teacher training Program.
­play school in hyderabad

Unknown said...

Menang saat bermain poker merupakan idaman setiap bettor termasuk anda sendiri. Namun terkadang kala apa yang kita harapkan tidak sesuai yang terjadi saat kita bermain.
asikqq
http://dewaqqq.club/
http://sumoqq.today/
interqq
pionpoker
bandar ceme
freebet tanpa deposit
paito warna terlengkap
syair sgp

luckys said...

english to marathi typing   

Bharat said...

Wonderful blog post, thank you so much for the great information which you provided.
Top 5 features of salesforce lightning

Bharat said...

Wonderful blog post, thank you so much for the great information which you provided.
Salesforce Lightning Training in Hyderabad

kirankumar said...

Thanks for providing information and it is understandable

Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,Welding Inspector Course, Quality Management Course, #Safety officer course.
Welding Inspector Course
Safety officer course
Quality Management Course
Quality Management Course in India

Edward Kent said...

If you are looking for the Salesforce B2C-Commerce-Developer Dumps Visit Exams4sure once. Exams4sure is the best and authentic place to prepare and pass the exam on the first attempt. There are a lot of website providing B2C-Commerce-Developer Questions Answers but no one gives you authentic B2C-Commerce-Developer Practice Questions. Exams4sure experts team are highly qualified and compiled best B2C-Commerce-Developer Study Material for your Success. Try our B2C-Commerce-Developer Braindumps PDF demo free. Teachers recommended Exams4sure for the better exam results. We never compromised our quality. Get 40% discount today visit us to avail this offer.

Why Choose Exams4sure:

3 Months Free Updates
World-wide Valid
Real Exam Simulation
40% Discount
B2C-Commerce-Developer Real Exam Questions
100% Client Satisfaction
24/7 Customer Support

Get your B2C-Commerce-Developer Study Guide today.

akhilapriya404 said...

The information which you have provided is very good. It is very useful who is looking for salesforce online training in Hyderabad

salesforce Certifications said...

As you know, link Salesforce Community Cloud Sample Paper and its demand is increasing a lot today. If you want to get certified by the salesforce and are preparing for the exam then this is very beneficial for you. We have practice papers solved by experts which will make your exam easy. Through them, you will be able to understand what types of questions come and you can solve them in an easy way.

Unknown said...

Great post. Post Lwc components as well

Regards
Nice post. Keep posting on latest salesforce topics like lwc:
Gutta Salesforcepoint

Salesforce Developer said...

I really like it when individuals come together and share thoughts. Great blog, continue the good work!
Salesforce Lightning Developer

Amrita Bansal said...

Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
Manal testing Training in Gurgaon
Selenium Training in Gurgaon
Cucumber Training in Gurgaon
Microservices Testing Training in Gurgaon


Aleena said...

Thanks for sharing this article. Please check our website for all new article. Auditing Companies in Dubai

Jiju said...

Best and very informative article. Thanks for sharing this article. Please check our website for all new article. ICV Certificate

Safreena said...

Thanks for sharing this article. please check our website for all new article. Auditors in Dubai

Daniel Charissa said...

Thanks for this valuable code. Keep share more informative code. ICV Certificate

Joseph said...

Useful and effective. Thanks for sharing this article. for more details click here ICV Certification

walker said...

AlmaMate offers the best Salesforce training in Noida. It is actually regarded as one of the best training institutes in

Noida for Salesforce. We offer best-in-class SFDC development training not only in Noida but in pan India location. The

Salesforce training provided by us is devised to make you ready to deploy.

Our Salesforce training is aligned with the industry standards and it has been designed in keeping in view all the

necessary inclusions. AlmaMate ensures 100% placement assistance after successful completion of your training. If you are

looking forward to making your career in the Information Technology domain then join the best Salesforce training in

Noida.To get further details of our services simply decision India at: (Toll Free) US: +91 9315269123
Best Salesforce Training in Noida
Best Salesforce Training in Delhi
Salesforce Training in Noida

Kailey Robinson said...

Thanks for the always useful information. This is great information to help peoples and nice article written by writer. CnX Player is a powerful & efficient 4K ultra HD enabled video player for Windows 10 PC & Tablet, Android and iOS – iPhone & iPad.

Download Media Player for Windows 10 - Microsoft Store
Download Video Player for Android from Google Play
Download Video Player for iPhone/iPad from Apple App Store

Aptron Gurgaon said...

Thanks for Sharing this Information. Salesforce Training in Gurgaon

web24zone said...

Development Company in Lucknow

Post a Comment

 
| ,