how to control what year datepicker goes to in salesforce

Salesforce Lightning is a great tool for building modular, extensible and mod UIs on the Salesforce platform.

Salesforce Lightning Datepicker

In that location are a lot of pre-built UI controls that you tin can use to create an interface in Salesforce, just there are a couple of vital missing pieces.

The offset of these is the Lookup component, which I wrote almost in a previous mail, "Embed a Lightning Component in a Visualforce Pagecur". The 2nd is a skilful, Salesforce Lightning Pattern Arrangement styled Datepicker component. At that place is an existing component, only it is non lightning styled and integrating it into a Lightning App often causes style problems.

Salesforce have divers what they think a picker should look similar on their extensive Salesforce Lightning Pattern Arrangement style site, which contains extensive resource to help developers create cute UIs – yous tin can encounter their definition here.

What I am going to testify is how to create your own Lightning Datepicker component.

Notation: This datepicker has been configured for U.S.-based locales. For international use, you may need to do your ain customization.

Background

To build this component, I used several sources – however, equally the result is kind of a mashup, I haven't included an licence data, as almost of the code is my own.

  • I used some of the structure of the existing Aura lightning component hither.
  • I also used some data structures and ideas from here.

Finally, I was forced to utilise moment.js despite trying not to have whatever external dependencies, but due to a bug in the Lightning framework – (the $A.localizationService.parseDateTime() method seems to exist blocked by the Locker Service), I was forced to use it for string to date conversions.
Get moment hither.

            <aureola:result type="COMPONENT" description="Dispatched when a date cell is clicked" />          

The date change event – the parameter is a string containing the value of the selected date.

            <aura:event type="COMPONENT" clarification="Despatched when the date is changed in the DatePicker component" >   <aura:attribute name="value" type="String" description="string value of the selected date" access="global" /> </aureola:event>          

Side by side, you need to ascertain a "DateCell" component – this represents a single day in the date grid. As you tin can run into, the DateCellClick consequence is registered as an event that can be dispatched by this component.

            <aureola:component >     <aureola:attribute proper name="ariaSelected" type="String" default="false" description="Highlight this control."/>     <aura:attribute name="ariaDisabled" type="String" default="false" description="Disable this control."/>     <aura:attribute name="tabIndex" blazon="Integer" default="-1" clarification="The tab index of the anchor element."/>     <aura:attribute name="value" type="Engagement" description="The date this component renders."/>     <aura:attribute name="label" blazon="String"/>     <aura:attribute name="tdClass" blazon="String"/>     <td form="{!5.tdClass}" role="gridcell" aria-selected="{!v.ariaSelected}" aria-disabled="{!5.ariaDisabled}" onclick="{!c.handleClick}" >        <span grade="slds-day" >{!v.label}</bridge>     </td>     <aura:registerevent proper noun="dateCellClick" type="c:DateCellClick" clarification="click event" /> </aureola:component>          

For this component, I utilize a simple controller, which refires a standard "onclick" outcome as a Lightning DateCellClick event.

            ({     handleClick : role(component, event, helper) {         var click = component.getEvent("dateCellClick");         click.burn down();     } })          

Now nosotros tin can define the chief component. This component uses pre-rendered cells (similar the original Aura DateGrid), which means it's easy to place private cells and return the day values before and after the electric current month.

There are ii main parts to the filigree. Beginning a uncomplicated ui:inputText:

            <div class="slds-class-chemical element ">   <label class="slds-form-element__label" for="closedate">{!v.characterization}</label>   <div class="slds-form-element__control">     <div class="slds-input-has-icon slds-input-has-icon--correct">       <c:SVG class="slds-input__icon slds-icon-text-default icon--large" xlinkHref="{!$Resource.SLDS105 + '/assets/icons/standard-sprite/svg/symbols.svg#result'}"></c:SVG>       <ui:inputDate aura:id="dateInput" class="slds-input" value="{!5.value}" format="{!v.formatSpecifier}" displayDatePicker="simulated" updateOn="keyup" focus="{!c.handleInputFocus}" />     </div>   </div> </div>          

This code holds the date and formats it for output.

Next, there is the filigree:

            <div aura:id="grid" class="slds-datepicker slds-dropdown slds-dropdown--left slds-hide" onmouseleave="{!c.handleGridMouseLeave}" onmouseenter="{!c.handleGridMouseEnter}">    <div class="slds-datepicker__filter slds-grid">      <div class="slds-datepicker__filter--month slds-grid slds-grid--align-spread slds-grow">        <div class="slds-align-centre">          <a onclick="{!c.goToPreviousMonth}" href="javascript:void(0);" class="slds-push button slds-button--icon-container">            <c:SVG class="slds-button__icon slds-button__icon--minor slds-m-top--small" xlinkHref="{!$Resource.SLDS105 + '/assets/icons/utility-sprite/svg/symbols.svg#left'}">            </c:SVG>          </a>        </div>        <h2 id="month" grade="slds-align-middle" aria-live="assertive" aria-atomic="true">{!5.monthName}</h2>        <div class="slds-align-middle">          <a onclick="{!c.goToNextMonth}" href="javascript:void(0);" class="slds-push button slds-push--icon-container">            <c:SVG class="slds-button__icon slds-button__icon--small slds-thousand-top--modest" xlinkHref="{!$Resource.SLDS105 + '/assets/icons/utility-sprite/svg/symbols.svg#right'}">            </c:SVG>          </a>        </div>      </div>      <div class="slds-shrink-none">        <ui:inputSelect aura:id="yearSelect" form="slds-select spear-select" label="selection a twelvemonth" labelClass="slds-assistive-text" required="false" modify="{!c.handleYearChange}" />      </div>    </div>    <table aureola:id="maintable" grade="datepicker__month" role="grid" aria-labelledby="month">      <thead>        <tr id="weekdays">          <aura:iteration items="{!v._namesOfWeekdays}" var="day">            <th scope="col" class="dayOfWeek">              <abbr championship="{!mean solar day.shortName}">{!day.shortName}</abbr>            </th>          </aura:iteration>        </tr>      </thead>      <tbody>        <tr aureola:id="week1">          <c:DateCell aura:id="0" />          <c:DateCell aura:id="1" />          <c:DateCell aura:id="2" />          <c:DateCell aura:id="3" />          <c:DateCell aureola:id="four" />          <c:DateCell aureola:id="5" />          <c:DateCell aura:id="half-dozen" />        </tr>        <tr aureola:id="week2">          <c:DateCell aura:id="7" />          <c:DateCell aureola:id="8" />          <c:DateCell aura:id="9" />          <c:DateCell aura:id="x" />          <c:DateCell aura:id="eleven" />          <c:DateCell aura:id="12" />          <c:DateCell aureola:id="13" />        </tr>        <tr aureola:id="week3">          <c:DateCell aureola:id="14" />          <c:DateCell aura:id="15" />          <c:DateCell aura:id="sixteen" />          <c:DateCell aura:id="17" />          <c:DateCell aureola:id="eighteen" />          <c:DateCell aura:id="xix" />          <c:DateCell aura:id="twenty" />        </tr>        <tr aura:id="week4">          <c:DateCell aureola:id="21" />          <c:DateCell aureola:id="22" />          <c:DateCell aura:id="23" />          <c:DateCell aura:id="24" />          <c:DateCell aura:id="25" />          <c:DateCell aureola:id="26" />          <c:DateCell aura:id="27" />        </tr>        <tr aura:id="week5">          <c:DateCell aureola:id="28" />          <c:DateCell aureola:id="29" />          <c:DateCell aura:id="xxx" />          <c:DateCell aura:id="31" />          <c:DateCell aura:id="32" />          <c:DateCell aura:id="33" />          <c:DateCell aura:id="34" />        </tr>        <tr aura:id="week6">          <c:DateCell aura:id="35" />          <c:DateCell aureola:id="36" />          <c:DateCell aureola:id="37" />          <c:DateCell aureola:id="38" />          <c:DateCell aura:id="39" />          <c:DateCell aura:id="twoscore" />          <c:DateCell aureola:id="41" />        </tr>        <tr>          <td colspan="seven" role="gridcell"><a onclick="{!c.goToToday}" href="javascript:void(0);" form="slds-bear witness--inline-block slds-p-bottom--ten-small-scale">Today</a></td>        </tr>      </tbody>    </table>  </div>          

The code merely above the actual filigree cells is taken directly from the Lightning CSS guide – withal, I was forced to use an anchor tag enclosing the SVG chemical element, as using a regular push button seemed to create an unhandled click effect that caused a page refresh.

I wasn't able to take hold of that event and terminate its propagation, and then the ballast tag was the next best matter. Anyone who knows how to practise this, please contact me.

The controller contains some basic logic but easily most of the work to the handler. To be honest, I'g finding it hard to work out whether to put lawmaking in the controller or the handler. And then far, I've got a bit of both :).

The is some init code, which formats the date string supplied equally a parameter and builds the grid. The other code handles mouse events to prevent the grid from closing when active.

Finally, there are some handers for the diverse UI events that occur – clicking back, forward, selecting a year and selecting a twenty-four hours.

As soon as the A.localeHandler bug is fixed, I'll remove the moment dependency.

Here it is:

            ({   doInit: part(component, event, helper) {     for (var i = 0; i < 41; i++) {       var cellCmp = component.find(i);       if (cellCmp) {         cellCmp.addHandler("dateCellClick", component, "c.handleClick");       }     }     var format = component.go("v.formatSpecifier");     var datestr = component.get("v.value");     var langLocale = $A.go("$Locale.langLocale");     var momentDate = moment(datestr, 'MM/DD/YYYY');     var currentDate;     if(currentDate == zero || !currentDate.isValid()){       currentDate = moment().toDate();     }     else {       currentDate = momentDate.toDate();     }     helper.setDateValues(component, currentDate, currentDate.getDate());     // Set the outset day of calendar week     helper.updateNameOfWeekDays(component);     helper.generateYearOptions(component,currentDate);     var setFocus = component.go("five.setFocus");     if (!setFocus) {       component.set("v._setFocus", false);     }     helper.renderGrid(component);   },   handleInputFocus: part(component, result) {     var grid = component.discover("grid");     if (grid) {       $A.util.removeClass(filigree, 'slds-hide');       $A.util.removeClass(grid, 'slds-transition-hide');     }   },   handleGridMouseLeave: office(component, upshot) {     var grid = component.notice('grid');     if (grid) {       $A.util.addClass(filigree, "slds-transition-hide");     }     var timeout = window.setTimeout(       $A.getCallback(function() {         if (grid.isValid()) {           $A.util.addClass(grid, "slds-hibernate");         }       }), 2000     );     component.set up("v._windowTimeout", timeout);     },   handleGridMouseEnter: function(component, outcome) {     var grid = component.find('grid');     if (grid) {       $A.util.removeClass(filigree, 'slds-hide');       $A.util.removeClass(grid, 'slds-transition-hibernate');     }     var timeout = component.become("5._windowTimeout");     if (timeout){       clearTimeout(timeout);     }   },   handleYearChange : part (component, upshot, helper){     var newYear = component.find("yearSelect").get("five.value");     var date = component.get("five.date");     helper.changeYear(component,newYear,engagement);   },   handleClick: role(component, upshot, helper) {     console.log('Date picker controller click' + event);     helper.selectDate(component, event);   },   goToToday: function(component, event, helper) {     event.stopPropagation();     helper.goToToday(component, event);     render false;   },   goToPreviousMonth: function(component,effect,helper) {     result.stopPropagation();     helper.changeMonth(component, -ane );     return false;   },   goToNextMonth: function(component,issue,helper) {     event.stopPropagation();     helper.changeMonth(component, i);     return false;   } });          

Finally, the helper does some more than depression-level rendering and chemical element manipulation.

Using the picker in your form

Bold yous are using an Opportunity (obviously any object with a appointment would work), define the Opportunity as an attribute on your component:

            <aura:attribute proper name="opportunity" blazon="Opportunity" default="{ 'sobjectType': 'Opportunity',                              'Name': 'New Opportunity',                              'StageName': 'Some Stage' />          
            <aura:handler name="dateChangeEvent" event="c:DateChange" activeness="{!c.handleDateChange}" />          

In your form, put the below(once y'all have created it) as a top level fellow member of the form:

            <div class="slds-form-element slds-m-elevation--medium">     <c:DatePicker aura:id="closeDate" label="Close Date" placeholder="Enter a Date" value="{!five.opportunity.CloseDate}" formatSpecifier="MM/dd/yyyy" /> </div>          

Finally, in your controller or helper update your date:

            handleDateChange: function(cmp, event, helper) {   var dateSelector = event.getSource().getLocalId();   if (dateSelector == 'closeDate'){     var opp = cmp.get("5.opportunity");     opp.CloseDate = result.getParam("value");   } }          

It should all simply work!

Table Sample
Final Results

Get the DatePicker files

All the files are located on Github.

Enjoy!

Moving Forwards in Lightning

Have questions? Let us know in a annotate below, or contact our team directly. You can also check out our other posts on customizing your Salesforce solution.

wrightmorbigh.blogspot.com

Source: https://www.soliantconsulting.com/blog/build-lightning-date-picker/

0 Response to "how to control what year datepicker goes to in salesforce"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel