Monday, December 24, 2018

How to set or get picklist (drop down) values in Lightning Components

Through this blog, I am going explain different syntax which can be used to create drop down (picklist) in lightning along with setting their their default values and fetching the user selected values in controller.js functions.

So will start with basics, if we already know different picklist or dropdown values then we can directly specify then in lightning markup as shown in below syntax:

Static Picklist

<lightning:select name="cStat" label="Case Status" value="New" aura:id="statusPicklist" >
<option value="">choose one...</option>
<option value="New">New</option>
<option value="In Progress">In-Progress</option>
<option value="Resolved">Resolved</option>
<option value="Closed">Closed</option>
</lightning:select>


"value" attribute  in lightning:select helps in pre-populating the default picklist value.

If you need to fetch the selected picklist value in controller.js, then use below syntax:

var selectedPicklistValue= component.find(“statusPicklist”).get(“v.value”);

Attribute Association with lightning:select

You can associate any attribute with lightning select and use that in "value" attribute of lightning select as shown below:

<aura:attribute name="ltngSelectedvalue" type="string" default="New"/>
<lightning:select name="cStat" label="Case Status" 
value="{!v.ltngSelectedvalue}" aura:id="statusPicklist" >
<option value="">choose one...</option>
<option value="New">New</option>
<option value="In Progress">In-Progress</option>
<option value="Resolved">Resolved</option>
<option value="Closed">Closed</option>
</lightning:select>

So in controller, you can directly get the value of attribute associated with lightning:select in order to get selected value for picklist.

var selectedPicklistValue= = component.get(“v. ltngSelectedvalue”);

Dynamic Picklist

When you are not sure of picklist options, then you can use dynamic picklist option. Different scenarios includes like passing picklist options from apex controller or using describe to get values for custom fields (picklist) created in salesforce.

Scenario 1

If the picklist label (displayed on UI) and values are similar then you can create an attribute of type "List" and use "aura:iteration" to create picklist options dynamically on UI. Below is sample syntax:

<aura:attribute name="options" type="List" 
default="['New','In Progress','Resolved','Closed']"/>
<aura:attribute name="ltngSelectedvalue" type="string" default="New"/>
<lightning:select name="cStat" label="Case Status" 
value="{!v.ltngSelectedvalue}" aura:id="statusPicklist" >
    <aura:iteration items=”{!v.options}” var=”opt”>
<option value="{!opt}">{!opt}</option>
    </aura:iteration>
</lightning:select>

Scenario 2

If picklist label on UI and values corresponding to then are different, then you can create a wrapper in apex class which contains 2 variables and return list of wrapper as different picklist options to lightning component attribute.

Public class picklistWrapper{
Public string pickListLabel;
Public string pickListValue;
}

Below is sample apex class which can be used to get picklist values using wrapper variable

Now in lightning component, you can call this apex method to fetch case status values and set it in attribute of type "object".
<aura:attribute name="options" type="Object"/>
In controller, store response from apex in variable and set the aura attribute

var apexResponse=response.getReturnValue();
//set response to attribute value
component.set("v.options",apexResponse);

In order to learn how to call apex method from lightning component refer below URL:
Calling Apex Method from Lightning Component

Below is sample code:

<!-- set options attribute through controller.js function call-->
<aura:attribute name=”options” type=”Object”/>
<aura:attribute name="ltngSelectedvalue" type="string"/>
<lightning:select name="cStat" label="Case Status" 
value="{!v.ltngSelectedvalue}" aura:id="statusPicklist" >
    <aura:iteration items=”{!v.options}” var=”opt”>
<option value="{!opt.pickListValue}">{!opt.pickListLabel}</option>
    </aura:iteration>
</lightning:select>

How to get selected picklist value on change event

You can also use onchange event on lightning:select to store the selected value by user in some aura:attribute.

<aura:attribute name=”options” type=”Object”/>
<lightning:select name="cStat" label="Case Status" aura:id="statusPicklist" 
onchange="{!c.onChange}">
<aura:iteration items="{!v.options}" var="opt">
<option value="{!opt.pickListValue}">{!opt.pickListLabel}</option>
</aura:iteration>
</lightning:select>

In controller.js, use below function:

onChange: function (cmp, event, helper) {
var selPickListValue = event.getSource().get("v.value");
        console.log('******selPickListValue :'+selPickListValue );
}

Note:

  • Event handler helps in identifying which markup element have been changed.
  • You can use event to get user selected element. Suppose user change the dropdown, value then by using event methods you can identify which dropdown value was changed by user along with its value.
  • You can get any attribute value of component through which user interacted on UI. for example event.getSource().get("v.name") will return "cStat" which is name attribute in lightning select.

Hope this will help!!!

38 comments:

  1. This should help! Otherwise, I will be forced to contact you personally for clarifying a few questions. Let me check the sample code as well.

    ReplyDelete
    Replies
    1. I want to show the display value as NONE along with other picklist values.How can i achieve that?

      Delete
  2. Treasurebox provide you all the items which you will be get online in a single click in Auckland Newzealand. We provide you quality items and all types of outdoor furniture at lowest price.

    ReplyDelete
  3. serialS Are uploaded on pinoy1 tv .here you can watch pinoy lambingan videos and swertres result free of cost

    ReplyDelete
    Replies
    1. ou personally for clarifying a few questions. Let me check the pinoy tambayan however I really thought youd have one thing interesting

      Delete
  4. Pinoy Tambayan is another favorite category of Pinoy1tv. The Pinoy Tambayan shows are watched not only in the Philippines but across borders as well. These shows are most enjoyed by Filipinos as their high ratings tell us.

    ReplyDelete

  5. Get all the latest clicksud onlineseriale online of clicksud and all the seriale online daily on this blog.

    ReplyDelete
  6. Heya i am for the primary time here. I came across this board and I to find It truly useful & it helped me out a lot. I’m hoping to provide something back and help others such as you aided me. ui design agency san francisco

    ReplyDelete
  7. The next time I learn a weblog, I hope that it doesnt disappoint me as much as this one. I mean, I do know it was my option to learn, however I really thought youd have one thing interesting to say. All I hear is a bunch of whining about something that you may repair when you werent too busy looking for attention. ui design agency san francisco

    ReplyDelete
  8. Howdy! I simply would like to give a huge thumbs up for the good data you have here on this post. I will probably be coming again to your weblog for more soon. mobile phone mockup

    ReplyDelete
  9. Hi there, Could I copy that snapshot and implement that on my webpage? ipad sketch

    ReplyDelete
  10. Thanks, Sunil.
    Brilliant post and great solution that makes the code easy to read.

    ReplyDelete
  11. Doramasmp4 esperamos que la estés pasando genial viendo. DoramasMP4 siempre será el primero en tener el episodio, así que por favor marque y agréguenos en Facebook para actualizarlo.
    https://www.evernote.com/shard/s617/sh/badf8185-4565-1a82-d4d9-17abc7c71027/e5be45b0b13252eca414907f2b9ea0ee

    ReplyDelete
  12. Do you need Finance? Are you looking for Finance? Are you looking for finance to enlarge your business? We help individuals and companies to obtain finance for business expanding and to setup a new business ranging any amount. Get finance at affordable interest rate of 3%, Do you need this finance for business and to clear your bills? Then send us an email now for more information contact us now via (financialserviceoffer876@gmail.com) whats-App +918929509036 Dr James Eric Finance Pvt Ltd Thanks

    ReplyDelete
  13. watch all Turkish Dramas with English Subtitles free of cost.
    On our website you can watch all old and latest turkish dramas with English Subtitles. Visit our website and watch

    https://turkishsub.su/

    ReplyDelete
  14. Best Website for Watching colors TV shows is Bigg Boss 15 Online

    ReplyDelete
  15. Filem, Episod, bukan cincai drama, dailymotion, vimeo, google docs dan Download on https://kepalabergetar.watch/

    ReplyDelete
  16. I’m going to read this. I’ll be sure to come back. thanks for sharing. and also This article gives the light in which we can observe the reality. this is very nice one and gives in-depth information. thanks for this nice article... CISA Practice Braindumps

    ReplyDelete
  17. Amazing unique article direct to the point. Trust me the way you interact is literally awesome I do respect that so much. I will instantly get your rss feed to stay informed of any updates you make and as well take the advantage to share some vital information regarding the
    G21 Gen 4 – a Semi-Automatic Pistol which many are not yet informed of it advantages compared to the other Semi automatic revolvers. Not over demanding, I will also take the advantage to ask for your permission to join our 179.3k members TELEGRAM CHANNEL
    As to share with us your ideas or any latest update on your blog.
    Thanks .

    ReplyDelete
  18. Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article. but I put things off too much and never seem to get started pinoylambingan first drama site to release the latest episodes of All new Dramas

    ReplyDelete
  19. I simply would like to give a huge thumbs that for the good data entry.

    Kepala Bergetar Drama

    ReplyDelete
  20. thanks for sharing. and also This article gives the light in lotterysambadnight taking time and real hard work to make a great article.

    ReplyDelete
  21. Good website! I truly love how it is easy on my eyes it is.https://kissasiane.com/

    ReplyDelete
  22. Do you Need Instant Loan from $2,000 to $50,000,000.00 with no collateral required and receive a no obligation loan approval.We welcome the opportunity to show you how effective we are at helping our clients obtain the money they need to succeed. Our professional staff is available for a Free Consultation.At Patiala legitimate company Pvt , contact us now 2% interest rate, both long and short term cash reply to us (Whats App) number: +919394133968 patialalegitimate515@gmail.com 
    Mr Jeffery

    ReplyDelete
  23. Our company is into project funding, Loan, joint venture, Equity and we are globally willing to fund companies, Private bodies, Government bodies and we are ready to help you with any kind of financial needs. In-case you are interested with my company financial services do get back to me with Kindly get back to us: magmafincropp@gmail.com
    Whats-app us on +917896570143

    ReplyDelete
  24. Watch Asian Drama , Kshows, drama Asian Online for free releases in Korean, Taiwanese, Hong Kong, Thailand and Chinese with Eng sub on DramaCool
    DramacoolKissasian is a free streaming website to watch English Subbed and Dubbed Asian online.
    dramacoolkissasian.com

    ReplyDelete
  25. HOW I GO MY DESIRED XMAS LOAN AMOUNT $520,000.00 FROM A RELIABLE AND TRUSTED LOAN COMPANY LAST WEEK. Email for immediate response: drbenjaminfinance@gmail.com

    Hello everyone, Am here to testify of how i got my loan from BENJAMIN LOAN FINANCE(drbenjaminfinance@gmail.com) I don't know if you are in need of an urgent loan to pay bills, start business or build a house, they offer all kinds of loan. So feel free to contact Dr.Benjamin Scarlet Owen he holds all of the information about how to obtain money quickly and painlessly via Email: drbenjaminfinance@gmail.com

    and consider all your financial problems tackled and solved. Share this to help a soul right now, Thanks


    ReplyDelete
  26. Valuable information! Looking forward to seeing your notes posted. The information you have posted is very useful. Keep going on, good stuff. Thank you for this valuable information. Dramahood

    ReplyDelete
  27. Teleserye usually makes dramas and TV series like this one which is a huge success.

    ReplyDelete
  28. Click on the desired show when you have access to the best Pinoy Teleserye shows on our site.

    ReplyDelete
  29. This site provides you with all the content created by Lambingan.

    ReplyDelete
  30. Are you in need of Loan? Here all problem regarding Loans is solve between a short period of time what are you waiting for apply now and solve your problem or start a business with funds Contact us now. many more 2% interest rate.(Whats App) number +919394133968 patialalegitimate515@gmail.com
    Mr Sorina

    ReplyDelete
  31. [6:31 pm, 09/12/2021] +1 (804) 582-4540: It Tears me Up Whenever we receive complaints from Clients About Their Experience With the Hackers They Met Before They Heard about us.
    These Days There Are alot of Hackers Online, You Just Have to Be Careful about who you meet for help, because many people now don't know who to ask for help anymore but there's actually a solution to that which I am giving you for free, Don't go out there seeking for Hackers Yourself, Because the probability of getting a Real Hacker Out there Is Very Slim . ❌❌ ❌ Most Of Them are actually not who they say they're, they are just here to Rip people Off, You Can Always Identify Them With Their False Advertisements and False Testimonies Trying To Lure you Into their Arms, And most of them use yahoomails, gmails and other cheaper email providers which could easily expose their vulnerabilities, Please Don’t Fall For Them🚷 Come To Think Of It, Why would a Legit Hacker Be using a gmail or a cheap email provider that exposes his vulnerabilities????⚠️⚠️⚠️
    Well, Our Purpose Here Is To Link You Up With Top Legit Hackers With Great Online Reputations and Impressive LinkedIn Profiles That’ll Blow Your Mind.

    ☑️ COMPOSITE FIRMWARE SECURITY SPECIALISTS is here to Provide you with The Best Hackers, So you can get saved from The Arms of the Fake Hackers❌❌.


    ☑️All our Specialists are well experienced in their various niches with Great Skills, Technical Hacking Strategies And Positive Online Reputations And Recommendations🔘
    They hail from a proven track record and have cracked even the toughest of barriers to intrude and capture all relevant data needed by our Clients.

    We have Digital Forensic Specialists, Certified Ethical Hackers, Software Engineers, Firmware Security Experts, Private investigators and more. Our Goal is to make your digital life secure, safe and hassle free by Linking you Up With these great Professionals such as JACK CABLE, ARNE SWINNEN, SEAN MELIA, DAWID CZAGAN, BEN SADEGHIPOUR And More. These Professionals are Well Reserved Professionals who are always ready to Handle your job with great energy and swift response so that your problems can be solved very quickly.
    All You Need to Do is to send us a mail and we’ll Assign any of these specialists to Handle your Job immediately.

    ☑️ Below Is A Full List Of Our Services:
    ▪️ FUNDS RECOVERY ON SCAM INVESTMENTS, BINARY OPTIONS TRADING and ALL TYPES OF SCAMS.
    ▪️ WEBSITE AND DATABASE HACKING 💻
    ▪️ CREDIT REPAIR. 💳
    ▪️ PHONE HACKING & CLONING (giving you 📱 Unnoticeable access to everything Happening on the Target’s Phone)
    ▪️ CLEARING OF CRIMINAL RECORDS ❌
    ▪️ SOCIAL MEDIA ACCOUNTS HACKING 📱
    ▪️RECOVERY OF DELETED FILES 📤
    ▪️LOCATION TRACKING 📌
    ▪️BITCOIN MINING ⛏ And lot More.


    ☑️ CONTACT:
    .....
    firmwarehacks@gmail.com
    🔘2021 © composite firmware specialists
    🔘Want faster service? Contact us!
    🔘All Rights Reserved ®️

    ReplyDelete
  32. Mykshow123 Watch Asian Drama, drama asian Online free releases in Korean, Taiwanese, Hong Kong,Thailand and Chinese with English sub.
    Dramacool is the best platform offering you a good selection of dramas and kshow123.
    www1.mykshow123.com

    ReplyDelete