5 Replies Latest reply on Feb 4, 2007 11:57 AM by Dr._Goomba

    checkbox example

    KomputerMan.com Level 1
      Does anybody know where I can get an example that utilizes multiple checkboxes in a form?

      My challenge for today is as follows (well sort of like this anyway). I have one table that contains User information with UserCnt being the primary key. I have another table containing Colors (red, Green, Blue, Orange, Black, etc...) with ColorCnt (1, 2, 3, etc...) being the primary key. Finally I have a third linking table that allows me to link one person to multiple colors. Or in other words I have a many to many relationship between colors and people so one person can select many colors and one color can be selected by many people.

      What I have so far is a HBox with a custom component on the left panel that lists all of my users. On the right panel I have a different component that lists all of the colors in a <mx:Repeater section. What I want to do is be able to select a user from the left panel and have it put a check into the checkbox for all of the colors the person have previously picked. I.E. user one has selected Red and Green so only those two boxes should be checked when user one is selected. User two in the other hand likes Blue and Orange so only those two checkboxes should have a check in them when user two is selected from the list in the left panel. After I select a user I also want to be able to check or uncheck a box and save that data back into my database.

      So my question is does anybody know where there is some sample code that will solve a problem similar to this??? Thanks in advance for the help!!!

      Have an Ordinary Day...
      KomputerMan ~|:-)
        • 1. Re: checkbox example
          KomputerMan.com Level 1
          So why is this so hard to accomplish using Flex???

          To create this in CF all I do is run two queries, one query returns all of the colors in the table, the other query returns what colors are associated to the selected person. Then I put the results of the second query into a list called MyColorList. When I loop through the query containing all the colors this is all I do...
          <CFLOOP QUERY="GetAllColors">
          <CFOUTPUT><CFIF ListFind(MyColorList, ColorCnt) NEQ 0>
          <INPUT TYPE="Checkbox" NAME="#ColorCnt#" VALUE="#ColorCnt#" CHECKED>
          <CFELSE>
          <INPUT TYPE="Checkbox" NAME="#ColorCnt#" VALUE="#ColorCnt#">
          </CFIF></CFOUTPUT>

          It doesn't get much easier than that!!!

          Hate to tell Adobe this but if they can't make the simple things simple then I don't see how Flex will survive! To create a simple list of checkboxes that are dynamically checked should take 30 to 60 minutes MAX. If I can't create this simple array of checklists then what else can't I do using Flex??? I've been trying to get this to work for the better part of six hours now and am no closer to a soution than when I began. Maybe I was wrong to try learning Flex... And maybe I was wrong to recommend it to my clients.

          Not Having an Ordinary Day...
          KomputerMan ~|:-)
          • 2. Re: checkbox example
            KomputerMan.com Level 1
            Alright already... After much pain and turmoil I finally got the dang thing to work. Just because somebody else might have this problem I will post my solution here...

            My applet consists of 4 mxml templates, the main template and 3 components. one component doesn't have anything to do with this post so I am leaving it off. One component contains a datagrid that I use to select people with, the other component contains the checkboxes that I want to dynamically select and unselect. The main template calls in these two components.

            There are a bunch of action script templates that are also used to make this thing work. I have included them as well.

            Some of the code in here is used to process the checkboxes after I hit the submit button. This code creates a comma separated list of all the values contained in the checkbox to pass back to my CF Web Service. Once again the CF code is not included.

            Because there is a size limit to how much stuff I can put into one posting I am breaking it up into three different posts. This post will contain the main mxml template. The next post will contain the other two mxml components of interest. The third post will contain all of the AS templates. If you are trying to use this to solve your own populate the checkbox problem... well then... Good luck with this!!!

            Disclaimer goes here: This may not be the best way to do this or the only way to do this but it worked for me so here it is... I make no claims about the brilliance of this solution either!!! :)

            manageUsers.mxml:

            <?xml version="1.0" encoding="utf-8"?>
            <mx:Application xmlns:mx=" http://www.adobe.com/2006/mxml" layout="vertical" paddingBottom="5" paddingLeft="5"
            paddingRight="5" paddingTop="5" backgroundGradientColors="[#F5F5F5, #F5F5F5]" xmlns:comp="components.*"
            creationComplete="getAllUsers.getUsers(), getAllSecStuff.getSecRoles(), modUserInfoID.updateIt()"
            width="800" height="330">


            <!-- Create the scripts needed to return the data and handle the selected events. -->
            <mx:Script>
            <![CDATA[
            import mx.collections.ArrayCollection; // add the library that deals with Arrays
            import mx.rpc.events.ResultEvent; // Add the library that deals with Events.
            import mx.controls.Alert // add the alert event incase something happens to the add data command.
            import events.KDL_SelEvent; // Add the generic Event was selected handler
            import events.AddUserInfo; // Add the generic Event was selected handler
            import events.AddUserSecurity; // AddUserSecurity Event

            // Return the data for the Users
            [Bindable]
            private var allUsers:ArrayCollection;

            private function getUsersHandler(event:ResultEvent):void
            {
            allUsers = new ArrayCollection(event.result as Array);
            }

            // Return the data for the Security Roles
            [Bindable]
            private var allSecRoles:ArrayCollection;

            private function getSecRolesHandler(event:ResultEvent):void
            {
            allSecRoles = new ArrayCollection(event.result as Array);
            }

            // Kick off the a User was selected event for the user list. This calls a listener in the modUsersID component
            [Bindable]
            private var selectedUser:Object;

            private function userSelHandler(event:KDL_SelEvent):void
            {
            selectedUser = event.KDL_SelObject;
            }

            [Bindable]
            private var selectedUser2:Object;

            private function userSelHandler2(event:KDL_SelEvent):void
            {
            selectedUser2 = event.KDL_SelObject;
            getUserSec.getUserSecRoles(selectedUser2.UserCnt);
            }

            private function userAddedHandler(event:AddUserInfo):void // this is the listener for the add new user event.
            {
            // call the web service getAllUsers and the method addUserInfo and pass it the object containing the form variables.
            getAllUsers.addUserInfo(event.userToAdd);
            getAllUsers.getUsers();
            modUserInfoID.updateIt2()
            }

            private function userSecAddedHandler(event:AddUserSecurity):void // this is the listener for the add new user security event.
            {
            // call the web service getUserSec and the method addUserSecRights and pass it the object containing the form variables.
            getUserSec.addUserSecRights(event.userSec);
            }

            [Bindable]
            private var MyUpDateResults:String=new String();

            private function getUserEventStatus(event:ResultEvent):void
            {
            MyUpDateResults=event.result as String;
            if(MyUpDateResults == "ClaimTmp" )
            {
            Alert.show('Unable to delete the user because they are associated to a Claim Record.', 'Can Not Delete The User');
            }
            }

            // Return the the Security Roles for the user
            [Bindable]
            private var myUserSecRoles:ArrayCollection;

            private function getRolesHandler(event:ResultEvent):void
            {
            myUserSecRoles = new ArrayCollection(event.result as Array);
            Roles2TempID.getUserRoles();
            }

            ]]>
            </mx:Script>


            <!-- Link to the remote stylesheet -->
            <mx:Style source="ISIF_Flex.css" />

            <!-- Call the web services that return the users, security roles, and the associations between them -->
            <mx:RemoteObject id="getUserSec" destination="ColdFusion" source="ISIF.WebServices.Flex.UserData" showBusyCursor="true">
            <mx:method name="getUserSecRoles" result="getRolesHandler(event)" />
            </mx:RemoteObject>

            <mx:RemoteObject id="getAllUsers" destination="ColdFusion" source="ISIF.WebServices.Flex.UserData" showBusyCursor="true"
            result="getUserEventStatus(event)">
            <mx:method name="getUsers" result="getUsersHandler(event)"/>
            </mx:RemoteObject>

            <mx:RemoteObject id="getAllSecStuff" destination="ColdFusion" source="ISIF.WebServices.Flex.SecRoles" showBusyCursor="true">
            <mx:method name="getSecRoles" result="getSecRolesHandler(event)"/>
            </mx:RemoteObject>

            <mx:TabNavigator left="5" right="5" bottom="5" top="5" width="100%" height="100%" styleName="TabNavigator">

            <mx:Canvas label="System Users" width="100%" height="100%" id="SecTab" backgroundColor="#F5F5F5" activate="userListID.AddUserButton.visible=true">
            <mx:HDividedBox horizontalAlign="center" top="5" left="5" right="5" bottom="5">
            <mx:Panel id="UserPanel" title="System Users" width="45%" height="100%" styleName="Panel">
            <comp:UserList id="userListID" width="100%" height="100%"
            allSysUsers="{allUsers}" myclick="modUserInfoID.updateIt()"
            userSelected="userSelHandler(event), modUserInfoID.updateIt1()" />
            </mx:Panel>

            <mx:Panel id="UserInfoPanel" title="User Information" width="100%" height="100%" styleName="Panel"
            horizontalAlign="left" layout="horizontal" paddingLeft="2">
            <comp:UserInfo id="modUserInfoID" label="Modify the User Information"
            SelUserInfo="{selectedUser}" userAdded="userAddedHandler(event as AddUserInfo)" />

            </mx:Panel>
            </mx:HDividedBox>
            </mx:Canvas>

            <mx:Canvas label="Users to Security" width="100%" height="100%" id="AssocTab" backgroundColor="#F5F5F5">
            <mx:HDividedBox horizontalAlign="center" top="5" left="5" right="5" bottom="5">
            <mx:Panel id="UserPanel2" title="System Users" width="45%" height="100%" styleName="Panel">
            <comp:UserList id="userListID2" width="100%" height="100%" creationComplete="userListID2.AddUserButton.visible=false"
            allSysUsers="{allUsers}" userSelected="userSelHandler2(event)" />
            </mx:Panel>

            <mx:Panel id="Role2TempPanel" title="Modify The User to Security Roles" width="100%" height="100%" styleName="Panel"
            horizontalAlign="left" layout="horizontal" paddingLeft="2">
            <comp:UserSecRights id="Roles2TempID" userSecAdded="userSecAddedHandler(event as AddUserSecurity)"
            secRoles="{allSecRoles}" passSecRoles="{myUserSecRoles}" width="100%" height="100%" SelUserInfo="{selectedUser2}" />
            </mx:Panel>
            </mx:HDividedBox>
            </mx:Canvas>
            </mx:TabNavigator>

            </mx:Application>
            • 3. Re: checkbox example
              KomputerMan.com Level 1
              Part II of III

              UserList.mxml:

              <?xml version="1.0" encoding="utf-8"?>

              <!-- This tempate, UserListAll.mmxl is used to display all of the System Users in a drop down list format. -->

              <mx:VBox xmlns:mx=" http://www.adobe.com/2006/mxml" paddingLeft="10" paddingRight="10"
              paddingBottom="10" paddingTop="15" verticalGap="10" backgroundColor="#F5F5F5" horizontalAlign="center">

              <!-- Step one to creating a custom event is to specify the event using the Metadata tag -->
              <mx:Metadata>
              [Event(name="userSelected",type="events.KDL_SelEvent")]
              </mx:Metadata>

              <mx:Metadata>
              [Event("myclick")]
              </mx:Metadata>


              <mx:Script>
              <![CDATA[
              import mx.collections.ArrayCollection;
              import events.KDL_SelEvent;

              [Bindable]
              public var allSysUsers:ArrayCollection;

              // Creates the new event object by taking the extended class KDL_SelEvent, which contains an object that contains a string variable,
              // and dispatches it as a new event. Basically the event is just passing along the string argument which is the ID of the item
              // selected in the datagrid at this time.
              private function doClick():void
              {
              var eventObj:KDL_SelEvent = new KDL_SelEvent(systemUsersGrid.selectedItem,"userSelected");
              dispatchEvent(eventObj);
              }

              private function addButtonClick():void
              {
              dispatchEvent(new Event("myclick"));
              systemUsersGrid.selectedItem = "";
              }

              ]]>
              </mx:Script>

              <!-- Step 2 to creating a custom event is to create an event object such as this datagrid -->
              <mx:DataGrid id="systemUsersGrid" dataProvider="{allSysUsers}" change="doClick()" width="98%" height="185"
              styleName="DataGrid" fontFamily="Arial" fontSize="10" textAlign="left" fontWeight="bold">
              <mx:columns>
              <mx:Array>
              <mx:DataGridColumn dataField="FirstName" headerText="First Name" width="55" />
              <mx:DataGridColumn dataField="LastName" headerText="Last Name" width="105" />
              </mx:Array>
              </mx:columns>
              </mx:DataGrid>

              <mx:Button id="AddUserButton" label="Add System User" fontFamily="Arial" fontSize="10" fontWeight="bold"
              click="addButtonClick()" styleName="Button" />


              </mx:VBox>

              ***************************************************************************
              UserSecRights.mxml:

              <?xml version="1.0" encoding="utf-8"?>
              <mx:VBox xmlns:mx=" http://www.adobe.com/2006/mxml" borderStyle="none" borderThickness="3" paddingBottom="10"
              paddingLeft="10" paddingRight="10" paddingTop="10" >
              <!-- UserSecRights.mxml is a template that contains checkboxes that represent all of the available security roles. -->


              <!-- Create a MetaData event that declares something is ready to be added to the database. -->
              <mx:Metadata>
              [Event("userSecAdded", type="events.AddUserSecurity")]
              </mx:Metadata>

              <mx:Script>
              <![CDATA[

              import mx.collections.ArrayCollection;
              import mx.rpc.events.ResultEvent; // Add the library that deals with Events.
              import datamodels.User2SecModel;
              import events.AddUserSecurity;

              [Bindable]
              public var secRoles:ArrayCollection;

              [Bindable]
              public var SelUserInfo:Object; // used to pass in the values of the user that was selected in the datagrid

              [Bindable]
              public var passSecRoles:ArrayCollection; // used to pass in the values of the users rights that was selected in the datagrid

              public function getUserRoles():void
              {
              for(var y:int = 0; y < mySecRoles.length; y++)
              {
              mySecRoles[y].selected = false;
              }

              for(var i:int = 0; i < passSecRoles.length; i++)
              {
              for(var x:int = 0; x < mySecRoles.length; x++)
              {
              if(passSecRoles .SecCnt == mySecRoles[x].validationSubField)
              {
              mySecRoles[x].selected = true;
              }
              }
              }

              AddUserButton.visible=true;
              }

              // this calles the extended event, AddUserInfo, and passes in the form variables. This is the kickoff event.
              private function addSec():void
              {
              var userSec:User2SecModel=new User2SecModel(); // creating a usrSec variable that is modifying the User2Sec datamodel
              userSec.UserCnt=Input_UserCnt.text;

              var tmpSecCnt:String="";
              var firsttime:int = 0;

              for(var y:int = 0; y < mySecRoles.length; y++)
              {
              if (mySecRoles[y].selected == true)
              {
              if (firsttime == 0)
              {
              tmpSecCnt = mySecRoles[y].validationSubField;
              }
              else
              {
              tmpSecCnt = tmpSecCnt + "," + mySecRoles[y].validationSubField;
              }

              firsttime = firsttime + 1;
              }
              }

              userSec.SecCnt = tmpSecCnt;
              var eventObj:AddUserSecurity = new AddUserSecurity(userSec, "userSecAdded");
              dispatchEvent(eventObj); // dispatch the event that contains the form variables
              }

              ]]>
              </mx:Script>

              <mx:Label text="These are the Security Roles that are or can be associated to the User" width="400" textAlign="center" fontSize="11"/>
              <mx:Repeater id="rpData" dataProvider="{secRoles}">
              <mx:CheckBox id="mySecRoles" label="{rpData.currentItem.SecName}" validationSubField="{rpData.currentItem.SecCnt}"
              styleName="CheckBox" enabled="true" selected="false" />
              </mx:Repeater>

              <mx:Button visible="false" label="Modify User Security" id="AddUserButton" fontFamily="Arial" fontSize="10" fontWeight="bold"
              click="addSec()" styleName="Button" />

              <mx:TextInput visible="false" text="{SelUserInfo.UserCnt}" id="Input_UserCnt" />

              </mx:VBox>


              • 4. Re: checkbox example
                KomputerMan.com Level 1
                Part III of III

                User2SecModel.as:
                // ActionScript file User2SecModel.as that contains the data model of the User2Sec table.
                package datamodels
                {
                [RemoteClass(alias="ISIF.WebServices.Flex.UserData")]

                [Bindable]
                public class User2SecModel
                {
                public var UserCnt:String = "0";
                public var SecCnt:String = "";

                public function User2SecModel()
                {
                }
                }
                }


                ***************************************************************

                KDL_SelEvent.as:
                // ActionScript file KDL_SelEvent.as extends the Event Class and calls the new class KDL_SelEvent.
                // So I now have another class called KDL_SelEvent which contains a generic Object called KDL_SelObject which
                // contains the string value of them item that was selected in any component that calls this function.
                // Trying to make this a generic extension of the Event class.
                package events
                {
                // Imports the events class for compilation
                import flash.events.Event;

                // creating a new class called ClaimSelEvent, this gets called every time a new claimant gets selected from the list
                public class KDL_SelEvent extends Event
                {
                // creating a public object called KDL_SelObject,
                // this object is available to all objects in the application because of the public tag.
                public var KDL_SelObject:Object;

                // make the KDL_SelEvent a public object too. This class requires two parameters. 1st is the KDL_SelObject (item that was selected), the
                // 2nd is a type. This is called creating the constructor.
                public function KDL_SelEvent(KDL_SelObject:Object,type:String)
                {
                // the first line extends the type but I am not sure of what it is extending.
                super(type);
                // just sets the variable object to the object that was selected. Seems like extra work but that is how it works.
                this.KDL_SelObject = KDL_SelObject;
                }
                // basically telling the complier that we are coping and modifying the Event function,. we are not replacing it.
                public override function clone():Event
                {
                // this returns the selected claimant as an extension of the event class.
                return new KDL_SelEvent(KDL_SelObject,type);
                }
                }
                }


                *************************************************************************************

                AddUserSecurity.as:
                // ActionScript file AddUserSecurity .as to add a new User to the database or to modify an existing one.
                // This is a customized event that only works with User specific information.
                package events
                {
                import flash.events.Event;
                import datamodels.User2SecModel;

                public class AddUserSecurity extends Event
                {
                public var userSec:User2SecModel; // create a public variable that contains the user data model

                public function AddUserSecurity(userSec:User2SecModel,type:String)
                {
                super(type)
                this.userSec=userSec; // Creates a new event every time it is called.
                }

                public override function clone():Event
                {
                return new AddUserSecurity(userSec, type);
                }
                }
                }



                Hope this helps somebody...


                Have an Ordinary Day...
                KomputerMan ~|:-)
                • 5. Re: checkbox example
                  Dr._Goomba Level 1
                  Wow thats a lot of code to go through to find what it is you were trying accomplish. Here is a simple example for anyone wanting to use multiple checkboxes in a form:


                  <mx:Application xmlns:mx=" http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">

                  <mx:Script>
                  <![CDATA[

                  [Bindable]
                  private var myFruit:Array = [{name:"Bananas",id:3},{name:"Pineapple",id:5}];
                  [Bindable]
                  private var fruit:Array = [{name:"Apples",id:1},{name:"Oranges",id:2},{name:"Bananas",id:3},{name:"Grapes",id:4},{n ame:"Pineapple",id:5}];

                  private function init():void {
                  preselectFruit();
                  }

                  private function preselectFruit():void {
                  // loop through available fruits
                  for(var i:int = 0; i < this.fruit.length; i++) {
                  // loop through fruits i want
                  for(var x:int = 0; x < myFruit.length; x++) {
                  if(this.fruit .id == this.myFruit[x].id) {
                  // set selected field to true
                  selectedFruit
                  .selected = true;
                  //trace(this.fruit .name + " = " + this.myFruit[x].name);
                  }
                  }
                  }
                  }

                  private function updateFruit():void {
                  // loop over all heckboxes
                  for (var i:int = 0; i < this.selectedFruit.length; i++) {
                  // if selectedFruit is true
                  if (this.selectedFruit
                  .selected == true) {
                  trace("Name: " + this.selectedFruit .label + ", Id: " + this.fruit.id + " selected");
                  }
                  }
                  }

                  ]]>
                  </mx:Script>

                  <mx:Panel x="196" y="59" width="250" height="200" layout="absolute" title="Fruit">
                  <mx:VBox x="10" y="10">
                  <mx:Repeater id="fruitData" dataProvider="{this.fruit}">
                  <mx:CheckBox id="selectedFruit"
                  label="{fruitData.currentItem.name}"/>
                  </mx:Repeater>
                  </mx:VBox>
                  <mx:ControlBar>
                  <mx:Button label="Update" click="updateFruit()"/>
                  </mx:ControlBar>
                  </mx:Panel>

                  </mx:Application>