lunes, 8 de junio de 2015

SlickGrid. Dando formato a las celdas (I) - Formato básico

Artículos anteriores:
SlickGrid. Ejemplo básico (I) - Creando el primer grid
SlickGrid. Ejemplo básico (y II) - Añadiendo funcionalidad

Tras ver cómo crear un grid con funcionalidad básica con SlickGrid vamos a ver cómo podemos aplicar diferentes formatos al grid.

El formato de las celdas lo estableceremos a través de diferentes propiedades de las columnas. Con unas definiremos el tamaño de las columnas, en concreto:

- width: establece el ancho de la columna en pixels
- minWidth: establece el ancho mínimo de la columna en pixels. Por defecto tiene un valor de 30.
- maxWidth: establece el ancho máximo que puede tomar la columna en pixels.
- resizable: establece si el usuario puede cambiar el ancho de la columna. Por defecto tiene un valor de false.

Otras nos servirán para aplicar un estilo a la celda:

- cssClass: establece un nombre de clase que se aplicará a todas las celdas de datos de la columna.
- headerCssClass: establece un nombre de clase que se aplicará a la celda de cabecera de la columna.

Finalmente mostraré cómo utilizar una propiedad que nos permite tener un control total sobre el formato de visualización de los datos:

- formatter: establece una función que se encargará de realizar el formateo de la celda, recibiendo el dato a formatear y devolviendo el código html que representa el dato.

Creando la página de prueba

Para el ejemplo voy a paritr de un grid básico con información de 40 productos (los datos están obtenidos de la base de datos de pruebas AdventureWorks2012), para lo que voy a crear una nueva página html llamada FormatoColumnas.html.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Añadiendo Formato a Columnas</title>
    <link href="https://code.jquery.com/ui/1.11.4/themes/blitzer/jquery-ui.css" rel="stylesheet" />
    <link href="css/slick.grid.css" rel="stylesheet" />
    <link href="css/theme/slick-default-theme.css" rel="stylesheet" />
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
    <script src="Scripts/jquery.event.drag-2.2.js"></script>
    <script src="Scripts/slick.core.js"></script>
    <script src="Scripts/slick.grid.js"></script>
    <script type="text/javascript">
        var products = [
            { ProductID: 514, ProductNumber: "SA-M198", Name: "LL Mountain Seat Assembly", Color: null, StandardCost: 98.77, ProductSubcategoryID: null },
            { ProductID: 515, ProductNumber: "SA-M237", Name: "ML Mountain Seat Assembly", Color: null, StandardCost: 108.99, ProductSubcategoryID: null },
            { ProductID: 516, ProductNumber: "SA-M687", Name: "HL Mountain Seat Assembly", Color: null, StandardCost: 145.87, ProductSubcategoryID: null },
            { ProductID: 517, ProductNumber: "SA-R127", Name: "LL Road Seat Assembly", Color: null, StandardCost: 98.77, ProductSubcategoryID: null },
            { ProductID: 518, ProductNumber: "SA-R430", Name: "ML Road Seat Assembly", Color: null, StandardCost: 108.99, ProductSubcategoryID: null },
            { ProductID: 519, ProductNumber: "SA-R522", Name: "HL Road Seat Assembly", Color: null, StandardCost: 145.87, ProductSubcategoryID: null },
            { ProductID: 520, ProductNumber: "SA-T467", Name: "LL Touring Seat Assembly", Color: null, StandardCost: 98.77, ProductSubcategoryID: null },
            { ProductID: 521, ProductNumber: "SA-T612", Name: "ML Touring Seat Assembly", Color: null, StandardCost: 108.99, ProductSubcategoryID: null },
            { ProductID: 522, ProductNumber: "SA-T872", Name: "HL Touring Seat Assembly", Color: null, StandardCost: 145.87, ProductSubcategoryID: null },
            { ProductID: 680, ProductNumber: "FR-R92B-58", Name: "HL Road Frame - Black, 58", Color: "Black", StandardCost: 1059.31, ProductSubcategoryID: 14 },
            { ProductID: 706, ProductNumber: "FR-R92R-58", Name: "HL Road Frame - Red, 58", Color: "Red", StandardCost: 1059.31, ProductSubcategoryID: 14 },
            { ProductID: 707, ProductNumber: "HL-U509-R", Name: "Sport-100 Helmet, Red", Color: "Red", StandardCost: 13.09, ProductSubcategoryID: 31 },
            { ProductID: 708, ProductNumber: "HL-U509", Name: "Sport-100 Helmet, Black", Color: "Black", StandardCost: 13.09, ProductSubcategoryID: 31 },
            { ProductID: 709, ProductNumber: "SO-B909-M", Name: "Mountain Bike Socks, M", Color: "White", StandardCost: 3.40, ProductSubcategoryID: 23 },
            { ProductID: 710, ProductNumber: "SO-B909-L", Name: "Mountain Bike Socks, L", Color: "White", StandardCost: 3.40, ProductSubcategoryID: 23 },
            { ProductID: 711, ProductNumber: "HL-U509-B", Name: "Sport-100 Helmet, Blue", Color: "Blue", StandardCost: 13.09, ProductSubcategoryID: 31 },
            { ProductID: 712, ProductNumber: "CA-1098", Name: "AWC Logo Cap", Color: "Multi", StandardCost: 6.92, ProductSubcategoryID: 19 },
            { ProductID: 713, ProductNumber: "LJ-0192-S", Name: "Long-Sleeve Logo Jersey, S", Color: "Multi", StandardCost: 38.49, ProductSubcategoryID: 21 },
            { ProductID: 714, ProductNumber: "LJ-0192-M", Name: "Long-Sleeve Logo Jersey, M", Color: "Multi", StandardCost: 38.49, ProductSubcategoryID: 21 },
            { ProductID: 715, ProductNumber: "LJ-0192-L", Name: "Long-Sleeve Logo Jersey, L", Color: "Multi", StandardCost: 38.49, ProductSubcategoryID: 21 },
            { ProductID: 716, ProductNumber: "LJ-0192-X", Name: "Long-Sleeve Logo Jersey, XL", Color: "Multi", StandardCost: 38.49, ProductSubcategoryID: 21 },
            { ProductID: 717, ProductNumber: "FR-R92R-62", Name: "HL Road Frame - Red, 62", Color: "Red", StandardCost: 868.63, ProductSubcategoryID: 14 },
            { ProductID: 718, ProductNumber: "FR-R92R-44", Name: "HL Road Frame - Red, 44", Color: "Red", StandardCost: 868.63, ProductSubcategoryID: 14 },
            { ProductID: 719, ProductNumber: "FR-R92R-48", Name: "HL Road Frame - Red, 48", Color: "Red", StandardCost: 868.63, ProductSubcategoryID: 14 },
            { ProductID: 720, ProductNumber: "FR-R92R-52", Name: "HL Road Frame - Red, 52", Color: "Red", StandardCost: 868.63, ProductSubcategoryID: 14 },
            { ProductID: 721, ProductNumber: "FR-R92R-56", Name: "HL Road Frame - Red, 56", Color: "Red", StandardCost: 868.63, ProductSubcategoryID: 14 },
            { ProductID: 722, ProductNumber: "FR-R38B-58", Name: "LL Road Frame - Black, 58", Color: "Black", StandardCost: 204.63, ProductSubcategoryID: 14 },
            { ProductID: 723, ProductNumber: "FR-R38B-60", Name: "LL Road Frame - Black, 60", Color: "Black", StandardCost: 204.63, ProductSubcategoryID: 14 },
            { ProductID: 724, ProductNumber: "FR-R38B-62", Name: "LL Road Frame - Black, 62", Color: "Black", StandardCost: 204.63, ProductSubcategoryID: 14 },
            { ProductID: 725, ProductNumber: "FR-R38R-44", Name: "LL Road Frame - Red, 44", Color: "Red", StandardCost: 187.16, ProductSubcategoryID: 14 },
            { ProductID: 726, ProductNumber: "FR-R38R-48", Name: "LL Road Frame - Red, 48", Color: "Red", StandardCost: 187.16, ProductSubcategoryID: 14 },
            { ProductID: 727, ProductNumber: "FR-R38R-52", Name: "LL Road Frame - Red, 52", Color: "Red", StandardCost: 187.16, ProductSubcategoryID: 14 },
            { ProductID: 728, ProductNumber: "FR-R38R-58", Name: "LL Road Frame - Red, 58", Color: "Red", StandardCost: 187.16, ProductSubcategoryID: 14 },
            { ProductID: 729, ProductNumber: "FR-R38R-60", Name: "LL Road Frame - Red, 60", Color: "Red", StandardCost: 187.16, ProductSubcategoryID: 14 },
            { ProductID: 730, ProductNumber: "FR-R38R-62", Name: "LL Road Frame - Red, 62", Color: "Red", StandardCost: 187.16, ProductSubcategoryID: 14 },
            { ProductID: 731, ProductNumber: "FR-R72R-44", Name: "ML Road Frame - Red, 44", Color: "Red", StandardCost: 352.14, ProductSubcategoryID: 14 },
            { ProductID: 732, ProductNumber: "FR-R72R-48", Name: "ML Road Frame - Red, 48", Color: "Red", StandardCost: 352.14, ProductSubcategoryID: 14 },
            { ProductID: 733, ProductNumber: "FR-R72R-52", Name: "ML Road Frame - Red, 52", Color: "Red", StandardCost: 352.14, ProductSubcategoryID: 14 },
            { ProductID: 734, ProductNumber: "FR-R72R-58", Name: "ML Road Frame - Red, 58", Color: "Red", StandardCost: 352.14, ProductSubcategoryID: 14 },
            { ProductID: 735, ProductNumber: "FR-R72R-60", Name: "ML Road Frame - Red, 60", Color: "Red", StandardCost: 352.14, ProductSubcategoryID: 14 }
        ];

        $(function () {
   var columns = [
    { name: "ID", field: "ProductID", id: "ProductID" },
    { name: "Nº Producto", field: "ProductNumber", id: "ProductNumber" },
    { name: "Denominación", field: "Name", id: "Name" },
    { name: "Color", field: "Color", id: "Color" },
    { name: "Precio", field: "StandardCost", id: "StandardCost" },
    { name: "Categoría", field: "ProductSubcategoryID", id: "ProductSubcategoryID" }
   ];

   var grid = new Slick.Grid("#FormatGrid", products, columns);
        });
    </script>
 
</head>
<body>
    <div id="FormatGrid" style="width:1024px; height:500px;"></div>
</body>
</html>

Con esto obtenemos un grid básico sin más formato que el que establecen las hojas de estilo por defecto del SlickGrid y el tema de jQuery UI.

Grid básico

Establecer el tamaño de las columnas

Para establecer el ancho de las columnas utilizaré la propiedad width para definir el ancho inicial y, para controlar el redimensionamiento por parte del usuario, estableceré anchos mínimos y máximos con las propiedades minWidth y maxWidth, o que el ancho debe mantenerse fijo estableciendo a false la propiedad resizable.

var columns = [
    { name: "ID", field: "ProductID", id: "ProductID", width: 60, resizable: false },
    { name: "Nº Producto", field: "ProductNumber", id: "ProductNumber", width:120, resizable: false },
    { name: "Denominación", field: "Name", id: "Name", width: 250, minWidth: 150, maxWidth: 400 },
    { name: "Color", field: "Color", id: "Color", width: 80, minWidth: 60, maxWidth: 120 },
    { name: "Precio", field: "StandardCost", id: "StandardCost", width: 110, minWidth: 80, maxWidth: 170 },
    { name: "Sub", field: "ProductSubcategoryID", id: "ProductSubcategoryID", width: 60, resizable: false }
];

Si recargamos la página veremos que las columnas toman el ancho indicado y que únicamente puede cambiarse el tamaño de las columnas Denominación, Color y Precio, y sólo entre los límites establecidos.

Establecer ancho de columnas

Aplicar estilos a las celdas

A continuación voy a aplicar algunos estilos a las celdas a través de las propiedades headerCssClass (para aplicar estilos a las celdas de cabecera) y cssClass (para el resto de celdas).
He definido tres clases para aplicar: prKeyHeadColumn que establece el color de fondo para la cabecera del campo clave y que aplicaré a la cabecera de la columna ID, headColumn que establece el color de fondo para el resto de cabeceras y numericCell que establece alienación del texto a la derecha para las celdas numéricas y que aplicaré a las columnas ID, Precio y Subcategoría.

var columns = [
    { name: "ID", field: "ProductID", id: "ProductID", width: 60, resizable: false
     , headerCssClass: "prKeyHeadColumn", cssClass: "numericCell" },
    { name: "Nº Producto", field: "ProductNumber", id: "ProductNumber", width: 120, resizable: false
     , headerCssClass: "headColumn" },
    { name: "Denominación", field: "Name", id: "Name", width: 250, minWidth: 150, maxWidth: 400
     , headerCssClass: "headColumn" },
    { name: "Color", field: "Color", id: "Color", width: 80, minWidth: 60, maxWidth: 120
     , headerCssClass: "headColumn" },
    { name: "Precio", field: "StandardCost", id: "StandardCost", width: 110, minWidth: 80, maxWidth: 170
     , headerCssClass: "headColumn", cssClass: "numericCell" },
    { name: "Sub", field: "ProductSubcategoryID", id: "ProductSubcategoryID", width: 60, resizable: false
     , headerCssClass: "headColumn", cssClass: "numericCell" }
];
<style>
    .prKeyHeadColumn {
        background: rgba(204,0,0,0.2);
    }
    .headColumn{
        background: -webkit-linear-gradient(top, white, white 40%, rgba(204,0,0,0.2));
        background: -moz-linear-gradient(top, white, white 40%, rgba(204,0,0,0.2));
        background: -o-linear-gradient(top, white, white 40%, rgba(204,0,0,0.2));
        background: -ms-linear-gradient(top, white, white 40%, rgba(204,0,0,0.2));
    }
    .numericCell{
        text-align: right;
    }
</style>

Recargando la página comprobaremos el efecto.

Estilos aplicados a las celdas

Tras establecer un formato básico en nuestro grid, en el siguiente artículo veremos cómo podemos tener un mayor control sobre la forma de mostrar los datos a través de la propiedad formatter de las columnas.

El código


Puedes descargar el código de todos los ejemplos de SlickGrid de:



Artículo siguiente:
SlickGrid. Dando formato a las celdas (y II) - Formato avanzado

1 comentario: