15
Aug
07

Preventing a user from deselecting dates in a DateChooser control

Here’s an example which prevents users from deselecting a date in the Flex DateChooser control by Ctrl-clicking on the date. By listening for the DateChooser control’s change event, and if the currently selected date is null, we set the selected date to the previously selected date. Also, for no good reason, I added a List control which lets you disable certain dates in the calendar.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/15/preventing-a-user-from-deselecting-dates-in-a-datechooser-control/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.events.CalendarLayoutChangeEvent;

            private function dateChooser_change(evt:CalendarLayoutChangeEvent):void {
                /* Prevent deselecting of dates. */
                if (evt.currentTarget.selectedDate == null) {
                    evt.currentTarget.selectedDate = evt.newDate;
                }
            }
        ]]>
    </mx:Script>

    <mx:Array id="weekDayNames">
        <mx:String>Sun</mx:String>
        <mx:String>Mon</mx:String>
        <mx:String>Tue</mx:String>
        <mx:String>Wed</mx:String>
        <mx:String>Thu</mx:String>
        <mx:String>Fri</mx:String>
        <mx:String>Sat</mx:String>
    </mx:Array>

    <mx:String id="selDate">{dateChooser.selectedDate.toDateString()}</mx:String>

    <mx:HBox>
        <mx:VBox>
            <mx:DateChooser id="dateChooser"
                    disabledDays="{disabledDaysList.selectedIndices}"
                    selectedDate="{new Date()}"
                    dayNames="{weekDayNames}"
                    yearNavigationEnabled="true"
                    change="dateChooser_change(event)" />

            <mx:Label text="Selected date: {selDate}" />
        </mx:VBox>

        <mx:VBox>
            <mx:Label text="Disabled days:"    />
            <mx:List id="disabledDaysList"
                    width="100"
                    dataProvider="{weekDayNames}"
                    allowMultipleSelection="true" />
        </mx:VBox>
    </mx:HBox>

</mx:Application>

View source is enabled in the following example.


0 Responses to “Preventing a user from deselecting dates in a DateChooser control”


  1. No Comments

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".