5 Replies Latest reply on Aug 7, 2009 1:30 PM by Gregory Lafrance

    ComboBoxes inside dataGrid problem

    Jocrmo

      First of all, sorry for my english. I speak i write in spanish.

       

      I need help

       

      im doing a flex applicacion with Groovy and Grails. But this is not the problem.

       

      In flex i have a datagrid. inside the datagrid a have 2 colums and in any of these columns i have comboBox.

       

      --------------------------------------------------------------------------------
      |  column 1       |      column 2      |   other data            |
      --------------------------------------------------------------------------------
        combo1a              combo2a               xxxx
        combo1b              combo2b                xxxx
        combo1c               combo2c               xxxxx
         ...                              ...                      ...
      ------------------------------------------------------------------------------

       

      for example, if i select a value in combo1a i need to update the data in combo2a.

      Im trying to do that but when i select the value in combo1a all the combos in colum 2 are updated to the same data. this is my trouble because i need to update only he combo in the colum 2 that is in the same row of the selected combo in column 1.

       

      Can somebody help me please.

       

      i show yo my mxml file. Im ne in Flex.

       

       

       

      <?xml version="1.0" encoding="utf-8"?>
      <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="1439" height="686" backgroundGradientAlphas="[1.0, 1.0]" backgroundGradientColors="[#000106, #505153]">
         
          <!-- ============== Definicion de los metodos que manipularan los datos  ================-->
          <mx:Script>
              <![CDATA[
                  import mx.formatters.DateFormatter;
                  import Components.DateUtils;
                  import mx.utils.ArrayUtil;

       

                  import mx.controls.Alert;
                  import mx.events.DataGridEvent;
                  import mx.rpc.events.FaultEvent;
                  import mx.rpc.events.ResultEvent;
                  import mx.events.CalendarLayoutChangeEvent;
        
                  [Bindable]
                  public var idBit:int;       
                  [Bindable]
                  public var actividad:String;
                  [Bindable]
                  public var fecha:Date;
                  [Bindable]
                  public var horaInicio:Date;
                  [Bindable]
                  public var horaFin:Date;
                  [Bindable]
                  public var tipoTiempo:Number;
                  [Bindable]
                  public var fechaString:String;
                  [Bindable]
                  public var idProyecto:String;
                  [Bindable]
                  public var timeValues:Array = new Array(
                      "00:00", "00:15","00:30", "00:45",
                      "01:00", "01:15","01:30", "01:45",
                      "02:00" ,"02:15","02:30", "02:45",
                      "03:00", "03:15","03:30", "03:45",
                      "04:00", "04:15","04:30", "04:45",
                      "05:00", "05:15","05:30", "05:45",
                      "06:00", "06:15","06:30", "06:45",
                      "07:00", "07:15","07:30", "07:45",
                      "08:00", "08:15","08:30", "08:45",
                      "09:00", "09:15","09:30", "09:45",
                      "10:00", "10:15","10:30", "10:45",
                      "11:00", "11:15","11:30", "11:45",
                      "12:00", "12:15","12:30", "12:45",
                      "13:00", "13:15","13:30", "13:45",
                      "14:00", "14:15","14:30", "14:45",
                      "15:00", "15:15","15:30", "15:45",
                      "16:00", "16:15","16:30", "16:45",
                      "17:00", "17:15","17:30", "17:45",
                      "18:00", "18:15","18:30", "18:45",
                      "19:00", "19:15","19:30", "19:45",
                      "20:00", "20:15","20:30", "20:45",
                      "21:00", "21:15","21:30", "21:45",
                      "22:00", "22:15","22:30", "22:45",
                      "23:00", "23:15","23:30", "23:45");
                      [Bindable]
                      public var tiempo:Number=0;
                      [Bindable]
                      public var contador:Number=0;

       

                  private function sendItemData(event:DataGridEvent):void
                  {
                      var myEditor:TextInput = TextInput(event.currentTarget.itemEditorInstance);
                      //itemName = myEditor.text;

       

                      /*idBit = event.currentTarget.editedItemRenderer.data["idBit"];;       
                      actividad = event.currentTarget.editedItemRenderer.data["actividad"];;
                      fecha = event.currentTarget.editedItemRenderer.data["fecha"];;
                      horaInicio = event.currentTarget.editedItemRenderer.data["horaInicio"];;
                      horaFin = event.currentTarget.editedItemRenderer.data["horaFin"];;
                      tipoTiempo = event.currentTarget.editedItemRenderer.data["tipoTiempo"];;
                      //tarea = event.currentTarget.editedItemRenderer.data["tarea"];*/
                      //itemUpdateService.send();
                  }

       

                  private function AgregarItem():void
                  {
                    /*itemName = "";
                      itemBrand = "";
                      itemLine = "";
                      itemSaveService.send();*/
                      itemSearchService.send();
                  }
                 
                  /**
                  *  Funcion para eliminar un item del grid
                  *  @param Grid del cual se eliminara el item
                  */
                  private function EliminarItem(dg:DataGrid):void
                  {
                      // Se obtiene el id de la fila seleccionada
                     /*  itemId = dg.selectedIndex[1].toString();
                      itemDeleteService.send();
                      itemSearchService.send();
                      Alert.show("Se elimino la actividad con id: "+itemId);   */
                  }
                 
                  public function deleteItem(event:MouseEvent):void{
                      /* Alert.show("Eliminando un Item");     
                      itemId = dg.selectedItem.id;
                      Alert.show("Id del Item: "+itemId);
                      itemDeleteService.send(); */
                      //itemSearchService.send();
                     }
                 
                  protected function filterList():void
                  {
                      itemSearchService.send();
                  }
                 
                  protected function listarFecha(eventObj:CalendarLayoutChangeEvent):void
                  {
                      //Alert.show("************* Se selecciono una fecha en el calendario ");
                      lblTotalHoras.visible = false;
                      tiempo =  0;
                      contador =  0;
                      lbNoRegistros.text = "";
                      if (eventObj.currentTarget.selectedDate == null) {
                          return
                      }
                      lbFechaSeleccionada.text = DateUtils.fechaAsString(eventObj.currentTarget.selectedDate);
                     
                      fecha = eventObj.currentTarget.selectedDate;
                      //Alert.show("fecha seleccionada: "+fecha);
                      fechaString = DateUtils.dateFormat( fecha, DateUtils.SHORT_DATE_MASK );
                      //Alert.show("fecha enviada: "+fechaString);
                      itemSearchProyectosService.send();
                      itemSearchService.send();       
                      //Alert.show("************* Proyectos Service ");
                     // Alert.show("************* Proyectos "+itemSearchProyectosService.lastResult.toString());
                      //Alert.show("************* "+itemSearchService.lastResult.toString());
                  }

       

                  private function fault_Handler(event:FaultEvent):void
                  {
                      //Alert.show(event.fault.message, "Could not load items.");
                      lbNoRegistros.text = "No existen registros para la fecha!";
                      itemSearchProyectosService.clearResult();
                      itemSearchTareasProyectoService.clearResult();
                      lblTotalHoras.visible = false;
                      lbAlertaTiempo.text = "";
                      dg.dataProvider = "";
                     
                  }
                 
                  /**
                   * Initializing the screen for the first time it is opened
                   * @return void
                   */
                  private function initScreen():void {
                      /* Se cambia nombre de dias y meses del calendario */
                      tiempo =  0;
                      contador = 0;
                       calendario.dayNames= ['D', 'L', 'M', 'M', 'J', 'V', 'S'];      
                       calendario.monthNames =['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo','Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre','Diciembre'];
                      var hoy:Date = new Date();
                      fechaString = DateUtils.dateFormat( hoy, DateUtils.SHORT_DATE_MASK );
                       lbFechaSeleccionada.text = DateUtils.fechaAsString(new Date());
                      itemSearchService.send();
                      itemSearchProyectosService.send();
                  }
                      
                  /**
                   * Arma los labels a mostrar en el combo de proyectos
                   * dato que el label debera tener el numero de proyecto o reporte
                   * junto con la descripcion del proyecto
                   */
                  public function labelProyecto(proyecto:Object):String
                  {
                      return proyecto.label + proyecto.consecutivo +" - "+ proyecto.descripcion;
                  }
                 
                  /**
                  * Carga las tareas correspondientes a un proyecto.
                  * Especificamente al proyecto seleccionado.
                  */
                  public function loadTareasProyecto(combo:Object, dg:DataGrid):void
                  {
                        idProyecto = combo.dataProvider[combo.selectedIndex].id
                        Alert.show("Id del Proyecto Seleccionado "+ combo.dataProvider[combo.selectedIndex].id);
                        itemSearchTareasProyectoService.send();
                        //itemSearchTareasProyectoService.lastResult.tarea;
                       
                        //Alert.show("VAlor Combo "+data.comboProyectos.dataProvider[combo.selectedIndex].id);
                        //Alert.show("Indice Seleccionado "+ data.comboTareas.dataProvider[combo.selectedIndex].valueOf());
                   
                        //Alert.show(itemSearchTareasProyectoService.lastResult.toString());
                        //<!--dataProvider="{outerDocument.itemSearchTareasProyectoService.lastResult.tarea}"-->
                  }
                 
                  public function tareas(combo:Object, dg:DataGrid):void
                  {
                    // Adding a new task
                    Alert.show("Se dio un evento en el Grid "+dg.selectedIndex);
                    var rowIndex:int = dg.selectedIndex;
                    //Alert.show("tamaño provider " + dg.comboTareas.provider.length);
                    //var ct:Object =
                    /* if(e.rowIndex == tasks.length - 1)
                    {
                         */
                     /*  var txtIn:TextInput = TextInput(e.currentTarget.itemEditorInstance);
                      var dt:Object = e.itemRenderer.data;
                    
                      // Add new task
                      if(txtIn.text != ADD_TASK)
                      {
                        tasks.addItemAt(new Task(txtIn.text, 0, ""), e.rowIndex);
                      }
                    
                      // Destroy item editor
                      grid.destroyItemEditor();
                    
                      // Stop default behavior
                      e.preventDefault(); */
                   // }
                  }
                         
                  /**
                  * Obtiene el SelectedIndex del combo de hora Inicio, comparando los valores del combo
                  * con el valor del dataProvider del grid que se pasa como parametro.
                  * @param combo ComboBox para el cual se obtendra el selectedIndex
                  * @param date Hora de inicio que viene cargada en el dataProvider para la actividad especifica.
                  * @return int SelectedIndex que aparecera seleccionado en el ComboBox.
                  */
                  public function getInicio(combo:Object, date:String):int
                  {   
                        var tmp:Array = mx.utils.ArrayUtil.toArray(combo.dataProvider);
                        var dateFormat:DateFormatter = new DateFormatter();
                        dateFormat.formatString = "HH:NN";
                        var horaFormateada:String = dateFormat.format(date);
                      for ( var i:Number=0; i<tmp[0].length; i++ )  {  //loop over the items in the dataProvider
                             if ( tmp[0][i].toString() == horaFormateada)  {  //compare desired value to current item.data value
                              return i;
                             }
                        }
                        return 0;
                  }
                 
                  /**
                  * Calcula el total de tiempo para una actividad.
                  */
                  public function calcAndFormatTotal(item:Object, column:DataGridColumn):String {
                     
                      var horaI:String;
                      var minI:String;
                      var horaF:String;
                      var minF:String;

       

                      var dateFormat:DateFormatter = new DateFormatter();
                        dateFormat.formatString = "HH:NN";
                        var horaInicioString:String = dateFormat.format(item.horaInicio.toString());
                        var horaFinString:String = dateFormat.format(item.horaFin.toString());
                       
                        horaI = horaInicioString.substr(0, 2);
                      minI = horaInicioString.substr(horaInicioString.length - 2, 2);
                     
                     
                      horaF = horaFinString.substr(0, 2);
                      minF = horaFinString.substr(horaFinString.length - 2, 2);
                     
                      var horaInicio:Number = Number(horaI);
                      var tmp: Number = 0;
                      if (minI == "15")
                          tmp = 0.25;
                      if (minI == "30")
                          tmp = 0.50;
                      if (minI == "45")
                          tmp = 0.75;
                      horaInicio = horaInicio + tmp;
                     
                      var horaFin:Number = Number(horaF);
                      tmp = 0;
                      if (minF == "15")
                          tmp = 0.25;
                      if (minF == "30")
                          tmp = 0.50;
                      if (minF == "45")
                          tmp = 0.75;
                        horaFin = horaFin + tmp;
                       
                        //Alert.show("Date creado con hora inicio Formateada: "+fecha.toString());
                      var total:Number = horaFin - horaInicio;
                      var t:int = dg.dataProvider.length;
                     
                      if (contador <= t) {
                          if (contador != 1) {
                              tiempo = tiempo + total;
                          }
                          contador = contador + 1;
                      }
                      lbAlertaTiempo.text = tiempo.toString();
                     
                      if (total > 0)
                          lblTotalHoras.visible = true;
                      return total.toString();
                  }
              ]]>
          </mx:Script>
            
             <!-- ============== Definicion de los servicios web ================-->
            
          <mx:HTTPService id="itemSearchService"
              method="GET"
              url="http://jcruz:8080/memoranda/bitacoraService/search"
                resultFormat="e4x"
                fault="fault_Handler(event);"
                showBusyCursor="true">
                  <mx:request xmlns="">
                      <fecha>{fechaString}</fecha>
                  </mx:request>
            </mx:HTTPService>
           
            <mx:HTTPService id="itemSearchTareasProyectoService"
              method="GET"
              url="http://jcruz:8080/memoranda/bitacoraService/searchTareasProyecto"
                resultFormat="e4x"
                fault="fault_Handler(event);"
                showBusyCursor="true">
                  <mx:request xmlns="">
                      <idProyecto>{idProyecto}</idProyecto>
                  </mx:request>
            </mx:HTTPService>
           
            <mx:HTTPService id="itemSearchProyectosService"
              method="GET"
              url="http://jcruz:8080/memoranda/bitacoraService/searchProyectos"
                resultFormat="e4x"
                fault="fault_Handler(event);"
                showBusyCursor="true">
                  <mx:request xmlns="">
                  </mx:request>
            </mx:HTTPService>
           
            <!-- ============== Definicion los componentes de la vista ================-->
           
          <mx:Panel x="10" y="79" width="196" height="534" layout="absolute" borderColor="#B6B6C1">
              <mx:DateChooser id="calendario" x="0" y="0" width="176" height="157" enabled="true" change="listarFecha(event)" cornerRadius="16"/>
          </mx:Panel>
          <mx:Panel creationComplete="initScreen()" title="Registro de Actividades" height="534" width="1215" paddingTop="10" paddingLeft="10" paddingRight="10" x="214" y="79" borderColor="#BDBDC6" color="#D3E1E4">
              <mx:Label width="338" height="23" fontSize="13" fontWeight="bold" color="#42882D" enabled="true" id="lbFechaSeleccionada"/>
              <mx:Label text="Filtrar:" color="#060707"/>
              <mx:TextInput id="searchBox" enter="filterList();"/>
              <mx:Label id="lbNoRegistros" width="326" color="#F33111"/>
              <mx:DataGrid id="dg" width="100%" height="240" rowCount="5"
                          dataProvider="{itemSearchService.lastResult.bitacora}"
                          editable="true"
                          itemEditEnd="sendItemData(event);"
                          scroll="false" color="#0F1111">
                      <mx:columns>
                             <!--mx:DataGridColumn dataField="id" headerText="Id" editable="false" width="51"/-->
                          <!--mx:DataGridColumn dataField="actividad" headerText="Actividad" width="430"/-->
                          <mx:DataGridColumn dataField="horaInicio" headerText="Inicio" width="78" editable="false">
                              <mx:itemRenderer>
                                  <mx:Component>
                                      <mx:Canvas horizontalScrollPolicy="off">
                                          <mx:ComboBox id="comboInicio"
                                              selectedIndex="{outerDocument.getInicio(comboInicio, data.horaInicio.toString())}"
                                              dataProvider="{outerDocument.timeValues}"
                                              width="72">
                                              <!--mx:VBox>
                                                  <mx:DateFormatter id="formatDateTime" formatString="HH:NN" />
                                                  <mx:Label text="{formatDateTime.format(data.horaInicio.toString())}"/>
                                              </mx:VBox-->
                                          </mx:ComboBox>
                                      </mx:Canvas>
                                  </mx:Component>
                              </mx:itemRenderer>
                          </mx:DataGridColumn>
                          <mx:DataGridColumn dataField="horaFin" headerText="Fin" width="78" editable="false">
                              <mx:itemRenderer>
                                  <mx:Component>
                                      <mx:Canvas horizontalScrollPolicy="off">
                                          <mx:ComboBox id="comboFin"
                                              selectedIndex="{outerDocument.getInicio(comboFin, data.horaFin.toString())}"
                                              dataProvider="{outerDocument.timeValues}"
                                              width="72">
                                              <!--mx:VBox>
                                                  <mx:DateFormatter id="formatDateTime" formatString="HH:NN" />
                                                  <mx:Label text="{formatDateTime.format(data.horaInicio.toString())}"/>
                                              </mx:VBox-->
                                          </mx:ComboBox>
                                      </mx:Canvas>
                                      <!--mx:VBox>
                                          <mx:DateFormatter id="formatDateTime" formatString="HH:NN" />
                                          <mx:Label text="{formatDateTime.format(data.horaFin.toString())}"/>
                                      </mx:VBox-->
                                  </mx:Component>
                              </mx:itemRenderer>
                          </mx:DataGridColumn>
                          <mx:DataGridColumn dataField="actividad" headerText="Actividad" width="430"/>
                          <mx:DataGridColumn headerText="TT" width="55" editable="false">
                              <mx:itemRenderer>
                                    <mx:Component>
                                      <mx:Canvas horizontalScrollPolicy="off">
                                          <mx:ComboBox id="comboTiposTiempo"
                                              selectedIndex="{data.tipoTiempo == 0 ? 0:(data.tipoTiempo == 1 ? 1:(data.tipoTiempo == 2 ? 2:(data.tipoTiempo == 3 ? 3:0)))}"
                                              width="48">
                                              <mx:dataProvider>
                                                  <mx:Array>
                                                      <mx:String>N</mx:String>
                                                      <mx:String>E</mx:String>
                                                      <mx:String>ED</mx:String>
                                                      <mx:String>R</mx:String>
                                                  </mx:Array>
                                              </mx:dataProvider>
                                          </mx:ComboBox>
                                      </mx:Canvas>
                                      </mx:Component>
                              </mx:itemRenderer>
                          </mx:DataGridColumn>
                          <mx:DataGridColumn headerText="Proyecto" editable="false" width="300">
                                 <mx:itemRenderer>
                                <mx:Component>
                                  <mx:Canvas horizontalScrollPolicy="off">
                                      <mx:ComboBox id="comboProyectos"
                                          dataProvider="{outerDocument.itemSearchProyectosService.lastResult.proyecto}"
                                          labelField="consecutivo"
                                          prompt="{data.tareaProyectoDescripcion}"
                                          change="outerDocument.tareas(comboProyectos, outerDocument.dg)">
                                          <mx:labelFunction>
                                              outerDocument.labelProyecto
                                          </mx:labelFunction>
                                      </mx:ComboBox>
                                  </mx:Canvas>
                                  </mx:Component>
                              </mx:itemRenderer>
                          </mx:DataGridColumn>
                          <mx:DataGridColumn headerText="Tarea" editable="false">
                              <mx:itemRenderer>
                                <mx:Component>
                                  <mx:Canvas horizontalScrollPolicy="off">
                                      <mx:ComboBox id="comboTareas"
                                          labelField="descripcion"
                                          prompt="{data.tareaDescripcion}"/>       
                                  </mx:Canvas>
                                  </mx:Component>
                              </mx:itemRenderer>
                          </mx:DataGridColumn>
                          <mx:DataGridColumn id="grid2Total" headerText="Total" dataField="total" labelFunction="calcAndFormatTotal" width="45"/>
                             <mx:DataGridColumn headerText="" editable="false" width="25">
                              <mx:itemRenderer>
                                <mx:Component>
                                  <mx:LinkButton click="outerDocument.deleteItem(event)" icon="@Embed(source='../html-template/images/delete.png')"/>
                                </mx:Component>
                              </mx:itemRenderer>
                          </mx:DataGridColumn>
                     </mx:columns>
              </mx:DataGrid>
              <mx:Button label="Agregar" icon="@Embed(source='../html-template/images/add.png')" enabled="true" click="AgregarItem()" color="#0D0E0E">
              </mx:Button>
                  <mx:HBox width="1177" verticalScrollPolicy="off" horizontalScrollPolicy="off" horizontalAlign="right">
                      <mx:Label text="Total Horas" color="#265253" height="22" fontSize="12" fontWeight="bold" id="lblTotalHoras"/>
                      <mx:Label width="70" height="23" fontSize="13" fontWeight="bold" color="#EA1A10" enabled="true" id="lbAlertaTiempo" textAlign="left"/>
                  </mx:HBox>
          </mx:Panel>
          <mx:ApplicationControlBar x="10" y="1" width="1419" height="61" fillAlphas="[1.0, 1.0]" fillColors="[#2D2D30, #535357]">
              <mx:Label text="Memoranda" width="207" height="36" fontSize="20" color="#CEE5EA" fontWeight="bold" fontStyle="italic"/>
          </mx:ApplicationControlBar>
          <mx:ApplicationControlBar x="0" y="643" width="1439" height="43">
          </mx:ApplicationControlBar>    <mx:Label text="Consorcio Sysco Eprom 2009" color="#FDFFFF" width="1427" textAlign="center" x="10" y="659"/>
      </mx:Application>

        • 1. Re: ComboBoxes inside dataGrid problem
          Gregory Lafrance Level 6

          When you are doing something like this you need to always operate on the data provider of the datagrid. So when the user selects a value from ComboBox1, change the values in the dataprovider for ComboBox2.

           

          That is always the way to go.

           

          In some cases you need two data provider objects, the one with "all" the data, and the one reflecting what the user has selected for ComboBox1.

           

          If this post answered your question or helped, please mark it as such.

          1 person found this helpful
          • 2. Re: ComboBoxes inside dataGrid problem
            Jocrmo Level 1

            Thanks for your help.

             

            But i continue wtih my trouble.

             

            when i create the dataGrid a have a dataprovider, in this moment i have another data provider to load the column1 ComboBoxes, is the same dataProvider for all the comboBoxes in that column.

            When i take the change event in any combo in the column1 i create a function.

            This function will make the process to get the data to load the combo in column 2 (only one combo. The combo of the selected row). when i call a service this service bring the data and i use this data like dataProvider in the column 2 comboBox definition. The problem is tha when i change the data in this dataProvider all the combos by definition will updates his datas.

             

            How can i to update only the data in one especific combo in column 2.

             

            may you have son example or something like that.

             

            I have been reading, looking for samples but i dond found anything that can help me, i have two weeks working in a proyect with flex making research and in my job a have not people with flex aknowledge.

            • 3. Re: ComboBoxes inside dataGrid problem
              Gregory Lafrance Level 6

              Once again you need to access the data provider, but you need to use the row index and possibly column index.

               

              The change event will have the rowIndex and columnIndex and use this to change only the dataprovider field for that row/column.

              1 person found this helpful
              • 4. Re: ComboBoxes inside dataGrid problem
                Jocrmo Level 1

                i dont know how to acces that. i have the dataGrid object and i can take the

                row with  dg.selectedIndex but i dont know how to acces the data provider

                for a especific column and row (CELL) in a dataprovider. Sorry for dont know

                that but im new in flex.

                • 5. Re: ComboBoxes inside dataGrid problem
                  Gregory Lafrance Level 6

                  Now that I look at your code, you may be using dataprovider all wrong. You generally should not have to go to outerDocument and set the dataprovider of DataGrid itemRenderers from there. You should be able to set them based off the DataGrid dataProvider.

                   

                  See this link:

                   

                  http://livedocs.adobe.com/flex/3/html/help.html?content=cellrenderer_6.html

                   

                  If this post answered your question or helped, please mark it as such.