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!!!

25 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