• Publicidad (ayudanos a mantener el Foro haciendo un click sobre la misma)
  • Cuixer, una forma de administrar páginas web que nunca viste!

 Tema solucionado Ayuda con evento en un gridpanel

Foros generales de ayuda Ext 4.0.

Ext.foro.Nuevo
Mensajes: 8
Registrado: 04 Mar 2011, 13:07
NotaPublicado: 02 Feb 2012, 20:39
Resulta que tengo un gridpanel de la siguiente forma:
Código: Seleccionar todo
Ext.onReady(function(){
    var itemsPerPage = 10;   

    var store = Ext.create('Ext.data.Store', {
        id:'simpsonsStore',
        autoLoad: false,
        fields:['id', 'nombre', 'correo', 'user'],
        proxy: {
            type: 'ajax',
            url: '/json/usuario', 
            reader: {
                type: 'json',
                root: 'data',
                totalProperty: 'total'
            }
        }
    });

   
    store.load({
        params:{
            start:0,
            limit: itemsPerPage
        }
    });

    Ext.create('Ext.grid.Panel', {
        title: 'Usuario',
        store: store,
        columns: [
        {
            header: 'ID',
            dataIndex: 'id',
            editor: {
                xtype:'textfield',
                allowBlank:false
            }
        },
        {
            header: 'Nombre',
            dataIndex: 'nombre',
            editor: {
                xtype:'textfield',
                allowBlank:false
            }
        },

        {
            header: 'Email',
            dataIndex: 'correo',
            flex:1,
            editor: {
                xtype:'textfield',
                allowBlank:false
            }
        },

        {
            header: 'Usuario',
            dataIndex: 'user',
            editor: {
                xtype:'textfield',
                allowBlank:false
            }
        }
        ],
        selType: 'cellmodel',
        plugins: [
        Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 2
        })],
        height: 500,
        dockedItems: [{
            xtype: 'pagingtoolbar',
            store: store,   
            dock: 'bottom',
            displayInfo: true
        }],
        renderTo: 'user'
    });
});

Lo que hago es cargar los datos de la base de datos, pero necesito que cuando actualice cualquier dato en el grid poder capturar ese dato y mandarlo para que se inserte en la base de dato. Como se ve en el código ya tengo implementado el CellEditing, lo que no se es como tomar esos datos una vez estén editado…
Desde ya muchas gracias....
Para no ver esta publicidad, debes ser usuario del Foro.
Publicidad (ayudanos a mantener el Foro haciendo un click sobre la misma)


Cuixer, una forma de administrar páginas web que nunca viste!

Avatar de Usuario
Ext.foro.Nuevo
Mensajes: 6
Registrado: 09 Dic 2011, 13:31
NotaPublicado: 13 Feb 2012, 15:07
Hola amigo yo estoy desarrollando un proyecto en Ext Js, y tengo la solucion a tu problema, que esta mas detallado cuando cargue la grilla, al ahcer click a la fila de la grilla se cargara en el formulario, teniendo la opcion de mantenimiento por medio de estos botones que te lo incluyo, ademas se actualiza en la BD y en la grilla automaticamente : 8)

Código: Seleccionar todo
  <script type="text/javascript" >
  Ext.onReady(function(){

      var StoreCCS =new Ext.data.Store({
               remoteSort: true,
               baseParams: {clave:2,start:0,limit:11},
                 sortInfo: {field:'descripcion', direction:'ASC'},
                   proxy: new Ext.data.ScriptTagProxy({
                      url: 'CuentasContablesSoc',
                      waitMsg: 'Buscando...'
                 }),

                 reader: new Ext.data.JsonReader({
                     root: 'data',
                     totalProperty: 'total',
                     idProperty: 'cuentacontablesociedad_idcuentacontablesociedad',
                     fields: ['cuentacontablesociedad_idcuentacontablesociedad','cuentacontablesociedad_idsociedad_fk', 'cuentacontablesociedad_descripcion',
                        'cuentacontablesociedad_tipocuenta', 'cuentacontablesociedad_anexo', 'cuentacontablesociedad_estado', 'cuentacontablesociedad_cuentacontable' ]
                 })
      }) ;

       var GridCuentasContablesSociedad=new Ext.grid.GridPanel({   
             height:295,
              stripeRows: true,
              trackMouseOver:true,
              autoExpandColumn: 'cuentacontablesociedad_descripcion',
              store: StoreCCS,
              loadMask: {msg:'Cargando...'},
              textLoading: 'Cargando...',             
              columnLines: true,
            viewConfig: {
               forceFit: true
            },
             
             
              sm: new Ext.grid.RowSelectionModel({
                          singleSelect: true,
                          listeners: {
                              rowselect: function(sm, row, rec) {
                 PanelMainCuentasContablesSociedad.getForm().loadRecord(rec);
                                 
                              }
                          }
                      }),

                      columns: [new Ext.grid.RowNumberer({width: 30}),
                                { id: 'cuentacontablesociedad_idcuentacontablesociedad',   header: "ID. Cuenta Contable", dataIndex: 'cuentacontablesociedad_idcuentacontablesociedad', width: 130, sortable:true },
                              { id: 'cuentacontablesociedad_idsociedad_fk', header: "ID. Soc.", dataIndex: 'cuentacontablesociedad_idsociedad_fk', width: 50,  sortable:true },
                              { id: 'cuentacontablesociedad_descripcion', header: "Descripcion",  dataIndex: 'cuentacontablesociedad_descripcion',   width: 150, sortable:true },
                              { id: 'cuentacontablesociedad_tipocuenta', header: "Tipo Cuenta", dataIndex: 'cuentacontablesociedad_tipocuenta', width: 60, sortable:true },
                              { id: 'cuentacontablesociedad_anexo', header: "Anexo", dataIndex: 'cuentacontablesociedad_anexo', width: 60, sortable:true },
                              { id: 'cuentacontablesociedad_estado', header: "Estado",dataIndex: 'cuentacontablesociedad_estado',   width: 60, sortable:true },
                              { id: 'cuentacontablesociedad_cuentacontable', header: "Cuenta Contable",  dataIndex: 'cuentacontablesociedad_cuentacontable',   width: 70, sortable:true },
                                                           
                              {
                               xtype: 'actioncolumn',
                               width: 30,
                               header: "Ver",
                               tooltip:'Ver Detalle...',
                               items:[{
                                        icon   : 'imagenes/icons/application_view_detail.png', 
                                        tooltip: 'Ver Detalle',
                                     handler: function(grid, rowIndex, colIndex) {
                                     
                                     //recuperar la data al formulario
                                      grid.getSelectionModel().selectRow(rowIndex);
                                      var rec = StoreCCS.getAt(rowIndex);
                                     PanelMainCuentasContablesSociedad.getForm().loadRecord(rec);
                                     
                                     //fijar los datos de loc campos con los de los controles sino no funcionara.
                                       
                                   }
                                  }]
                             }
                              ],

             bbar: new Ext.PagingToolbar({
                store: StoreCCS,
                pageSize:11,
                 displayMsg: 'Mostrando {0} - {1} de {2} Registros',
                  emptyMsg: "No existe datos para mostrar",
                  firstText : "Primer Registro",
                  prevText : "Registro Anterior",
                  nextText : "Siguiente Registro",
                  lastText : "Ultimo Registro",
                  beforePageText : "P&aacute;g",
                  afterPageText : " de {0}",
                  displayInfo: true
               
             }),
            
            
             tbar: [
                  
                  ]
                           
         ,plugins:[new Ext.ux.grids.Search({
                mode:'local'
               ,iconCls:false
               ,dateFormat:'m/d/Y'
               ,minLength:2
               ,width:200
               ,position:'top'
              ,align:'left'
              ,tituloReporte: "Reporte de Catalogo"
              ,subtituloReporte: "Lista de Catalogo"
              ,tituloDocumento: "ListaGrupo"  //servletdestino
              ,subtituloDocumento: "Grupos de Tablas"
              
              ,activar:function(){ this.moreParameters["codigo"] = comboTipoCuenta.getValue();
                    this.moreParameters["descripcion"] = comboIndicadorAnexo.getValue();
                                        
                    }
              
              //,paginaImpresion: "administracion/printListado.jsp"
              ,botonCSV:false
              ,botonPDF:false
              ,botonRTF:false
              ,busqueda:true            
              ,parametros:[{clave:2},{params:{start:0, limit:100}}] 
           })]
         
            
         ,view: new Ext.ux.gridss.BufferView({
                // custom row height
                rowHeight: 20,
                // render rows as they come into viewable area.
                scrollDelay: false
             })
            
      });/////////////////////////////////////////////////FIN GRID

         StoreCCS.load({params:{start:0, limit:11, clave:2, activo:'S'}});

      var PanelMainCuentasContablesSociedad=new Ext.FormPanel({
         title:'Mantenimiento de Cuentas Contables y Sociedades',
          //  renderTo: Ext.getBody(),
               height: 250,
            width: 560,
            border:false,
            bodyStyle:'padding:10px 10px 10px',         
         defaults: { columnWidth:.130, height: 30,border:false },//afecta a todos los hijos(frame:true, para relieve)
          items:[
               {   colspan:5,height:17},
               //************************
                 {
                    xtype: 'hidden',
                    value:'0',
                  name:'cuentacontablesociedad_idcuentacontablesociedad',
                  id: 'idcuentacontablesociedad'
                  
                  },
                  {   
                     xtype          : 'textfield',
                     name           : 'cuentacontablesociedad_descripcion',                    
                     fieldLabel     : 'Descripcion', 
                       width         :230,
                       vtype         : 'uppercase',
                       height         :20
                   },
                   
                  {   
                     xtype          : 'textfield',
                     name           : 'cuentacontablesociedad_cuentacontable',                    
                     fieldLabel     : 'Cuenta Contable', 
                     labelWidth:120,
                     vtype: 'uppercase',
                  width:230,
                  height:20
                   },
                   
                   new Ext.form.RadioGroup({
                         fieldLabel: 'Tipo',
                          name : 'cuentacontablesociedad_estado',
                           columns: 2,
                           width:180,
                           items: [
                                {boxLabel: 'Activo', name: 'cuentacontablesociedad_estado', inputValue: 'A', checked: true},
                                {boxLabel: 'Inactivo', name: 'cuentacontablesociedad_estado', inputValue: 'I'}]
                         }),
                  
          ]
         //area de botones de mantenimiento
            ,buttons: [
                     {    buttonAlign : 'bottom',
                        tooltip:'Guardar Registro...',
                        iconCls:'save',
                        id:'btnsavecat',
                        waitTitle:'Connecting',
                        waitMsg:'Sending data...',
                        handler: function(btn, pressed){
                                    //funcion de grabacion del formulario
                                    guardarCuentaContable();
                        }
                        ,text: 'Guardar'
                     }
                     ,{
                        text : 'Eliminar',
                        buttonAlign : 'bottom',
                        tooltip:'Eliminar Registro...',
                        id:'btnelimcat',
                        icon: 'imagenes/images/cross.gif',
                        handler: function() {
                              Ext.Msg.show({
                                          title:'Confirmar',
                                          msg: 'Eliminar Registro?',
                                          buttons: Ext.Msg.YESNO,
                                          animEl: 'elId',
                                          fn: eliminarCuentaContable,
                                          icon: Ext.MessageBox.QUESTION
                              });
                        }
                     },
                     {
                        text : 'Limpiar',
                        buttonAlign : 'bottom',
                        tooltip:'Nuevo Registro...',
                        id:'btnnewcat',
                        icon: 'imagenes/icons/page_white.png',
                        handler: function() {
                        PanelMainCuentasContablesSociedad.getForm().reset();
                        }
                     }
            
            ]
      
         });
      //Panel GRID de Cuenta contable sociedad
      var PanelGridCuentasContablesSociedad=new Ext.Panel({
                title:'Datos de cuentas contable sociedad',
                height: 320,
                width:560,
                border:false,
                   layout: 'table',
                items:[GridCuentasContablesSociedad]                                               
        
      });
      // PANEL PRINCIPAL !!!
      var PanelMainPrincipal=new Ext.Panel({
         height: 435,
         width: 560,
            renderTo: Ext.getBody(),
            layout:{
               type:'table',
               columns:1
             },
            items:[
                 {items:PanelMainCuentasContablesSociedad},
              {items:PanelGridCuentasContablesSociedad}
             ]
          
         });
      
   
   app.CuentasContTab=Ext.getCmp('CuentasContTab');
   app.CuentasContTab.add(PanelMainPrincipal);
   app.CuentasContTab.doLayout();

   //----------------------------- AREA DE FUNCIONES ------------------------------
   //----------------------------------------------------------------------------
   var refrescarLista = function(){
      StoreCCS.load({params:{start:0, limit:10000, clave:2}});
   };
   
   
   var guardarCuentaContable = function(){
      var objSend={clave:3};
      var arrFrmCuentaContable = "";
      //recoger datos del formulario quitandole el prefijio "corporacion_"
      arrFrmCuentaContable = app.formToArr(PanelMainCuentasContablesSociedad,"cuentacontablesociedad_");
      objSend["cuentacontable"] = arrFrmCuentaContable;
      //envio de datos al server usando ajax
      Ext.Ajax.request({
      url : 'CuentasContablesSoc',
      params :objSend,
      method: 'POST',
      success: procesaGrabarCuentaContable,
      failure: procesaGrabarCuentaContable
      });
      
   
   };
   
   var procesaGrabarCuentaContable = function(result,request){
      var objDatos = result.responseText;
      json = Ext.util.JSON.decode(objDatos);
      
      //pegaDatosEnFormulario(objDatos)
      
      if(json)
      Ext.Msg.show({
      title:'Aviso',
      msg: json["msg"],
      buttons: Ext.Msg.OK,
      fn: refrescarLista,
      icon: Ext.MessageBox.WARNING
      });
      
      //refrescar la lista de registros guardados
   
   };
   
   var eliminarCuentaContable = function(opcion){
         //eliminar la corporacion
         
         //Si acepto eliminar
         if(opcion == 'yes'){
         var cod = parseInt( Ext.getCmp('idcuentacontablesociedad').getValue());
         //colocar la referencia en el servlet
         var objSend={clave:4, idcuentacontablesociedad:cod};
         //si el codigo es 0 no elimina nada
         if(cod==0){
         Ext.Msg.show({
         title:'Aviso',
         msg: 'Debe elegir un registro antes!!!',
         buttons: Ext.Msg.OK,
         icon: Ext.MessageBox.WARNING
         });
         return;
         }
         
         //si el codigo es <> de 0
         Ext.Ajax.request({
         url : 'CuentasContablesSoc',
         params :objSend,
         method: 'POST',
         success: procesaGrabarCuentaContable,
         failure: procesaGrabarCuentaContable
         });
         }
   };
  });
   
   
  </script>


Y aqui esta el codigo del servlet donde envia la data por medio de Ajax, ya sabes te lo recorto un poco por confidencialidad, pero si tienes dudas me pregantas a mi correo (nanatsuiro_drops@hotmail.com), aqui te doy tambien el Servlet :

Código: Seleccionar todo

public class CuentaContableServlet extends PadreServlet {

   private static final long serialVersionUID = 6269237612410508882L;
   private AdministracionFacadeInterfaceRemote administracionFacadeInterfaceRemote;
   
   @Override
   protected void delegaEnHijo(HttpServletRequest req, HttpServletResponse res)
         throws Exception {
      switch (opcion){
      
      case 2:
         //sera separado el objeto grilla para la carga individual
         String activo = getElementFromParameterValor("activo","S");
         activo.equals("S");      
         ArrayList<CuentaCS> lstCuenta = new ArrayList<CuentaCS>();
         //recuperar la lista de las corporaciones
         QueryReporte queryReporte = new QueryReporte();
         
                  
         //****************  PAGINACION  ************************
         //tienes que fijarte bien
         paginacionBean.setSort(paginacionBean.getSort().replaceAll("cuentacontablesociedad_", ""));
         
         Utiles.depuraBean(paginacionBean);
         Utiles.depuraBean(busquedaBean);
         
         //String fieldss =""
         //if(busquedaBean.getFields()!=null){
         //   fieldss = fieldss.replaceAll("rubroestadofinanciero_", "");// aca coloca el prefijo apra que lo quites
         //   busquedaBean.setFields(fieldss);
         //}   
         
         //1. crear el query
         String sql = queryReporte.getSQLListaCuentaCS(paginacionBean,busquedaBean);
         
         atributoValorBean = ejbSesion.getDataFromDS(sql);
         atributoValorBean.setAtributo(String.valueOf(ejbSesion.getNumRegistros())); //faltaba esta linea
         //con eso esta solucionado verifiquemos
         
         impresion = callback+"({\"total\":\""+ atributoValorBean.getAtributo()+"\",\"data\":"+
                     atributoValorBean.getValor()+"});";   
         
         //2. utilizar la funcion del FWK para insertar la consulta y obtener una lista de objetos
         //coloca un tope maximo de registro a obetener, sirve como regulador
         ejbSesion.setMaxRecordSubLista(1000);
         //se crea la lista de objetos ingresando el SQL y el nombre de la tabla
         ArrayList<Object> lstCuentasCS = ejbSesion.getDataFromDSToList(sql, "cuentacontablesociedad");
         
         
         
         //Se castea al Objeto Corporacion.//si no existe se crea
         for(Object o : lstCuentasCS){
            CuentaCS cuentacontablesociedad = new CuentaCS();
            BeanUtils.copyProperties(cuentacontablesociedad, o);
            lstCuenta.add(cuentacontablesociedad);
         }
         
         PrintWriter out = res.getWriter();
         
         String jsonContable = JSONUtil.serialize(lstCuenta);
         String njson = Utiles.addPrefijoToJson(jsonContable, "cuentacontablesociedad_");
         
         System.out.println("njson:"+njson);
         
         // impresion importante para que el njson capture toda la data contenida en el query ya antes declarado !!!!
         impresion = callback+"({\"total\":\""+ atributoValorBean.getAtributo()+"\",\"data\":"+
         njson+"});";
      
         out.print(impresion);
         //manos a la obra.
         
         
         break;
      case 3: //grabacion de data
         
         mensaje = "No se pudo guardar Ningun Registro";
         //framework
         ejbSesion.setMensaje("");
         //Se recupera en una clase con la estructura del formulario
         CuentaContableJSON cuentacontableJSON= (CuentaContableJSON) Utiles.parametersToObjAll(lstParametros, new CuentaContableJSON());
         //obtencion del objeto desde json
         CuentaCS cuentacs = (CuentaCS) Utiles.fromObjJsonToBean(cuentacontableJSON.getCuentacontable(), new CuentaCS());
         Utiles.depuraBean(cuentacs);
         //para ver la consulta
         //verificacion si es actualizacion o insercion de registro
         if(cuentacs.getIdcuentacontablesociedad()>0){ //actulizacion
            ejbSesion.setBean(cuentacs);
            ejbSesion.actualizaRegistro();
         }else{ //insrecion
            //generacion de Id
            CuentaCS ccs = new CuentaCS();
            //metodo directo al servicio del framework
            //obtencion del primer campo o campo ID
            String campo = CuentaCS.getAtributesToArray(ccs)[0];//idcorporacion
         
            //obtencion de la consulta de id
            String sqlId = QueryComunBean.getSQLMaxID(campo, "contable.cuentacontablesociedad", "",false);//SELECT max(idcorporacion) as id from corporacion.corporacion
            
            //ejecutar la consulta
            String idCCS = ejbSesion.lstRegistrosJson(sqlId);//[23]
            System.out.println("------------------idddddd:"+idCCS);
            //limpieza del dato
               if(idCCS.trim().equals("[]")) idCCS = "[0]";
               idCCS = Utiles.quitarCaracter(idCCS);//24
            
            //agregar el Id al Bean con datos
               cuentacs.setIdcuentacontablesociedad((new Integer(idCCS)+1));
               System.out.println("------------------agregar:"+((new Integer(idCCS)+1)));
               Utiles.depuraBean(cuentacs);
            //insercion
            ejbSesion.setBean(cuentacs);
            ejbSesion.agregarRegistro();
         }
         
         //envio del mensaje al cliente
         mensaje = ejbSesion.getMensaje();
         mensaje = "{success:true, msg:'"+mensaje+"'}";
         returnUTF(res, mensaje);
         
         break;
         
      case 4:
            ejbSesion.setMensaje("");
         
            //eliminacion de registro de corporacion
            String idCCSo = getElementFromParameterValor("idcuentacontablesociedad","0");
            
            //System.out.println("idcorporacion: "+idcorporacion);
            //con el id recuperar todo el objeto
            CuentaCS objCCS = (CuentaCS) ejbSesion.getObjectxId(new CuentaCS(), new Long(idCCSo));/////ojo:verificar el tipo Long
            
            //verificamos la recuperacion desde la bd
            //Utiles.depuraBean(objCorp);
            
            //eliminar logicamente el elemento
            ejbSesion.setBean(objCCS);
            ejbSesion.eliminaRegistro();
            
            mensaje = ejbSesion.getMensaje();
            mensaje = "{success:true, msg:'"+mensaje+"'}";
            returnUTF(res, mensaje);
            break;
   
      }
      
   }

   @Override
   public String getServletInfo() {
      return "CuentasContablesSoc";
   }
   

}


Por ultimo ya se detalla los querys que quieras en otro Servlet y los llamas usando Hibernate, tambien claro crea su bean de los campos de la tabla y listo. 8)

Volver a Ext 4.0: Ayuda





  • Publicidad (ayudanos a mantener el Foro haciendo un click sobre la misma)
  • Cuixer, una forma de administrar páginas web que nunca viste!