8.1kvistas

Hola todos, bien ahora toco hacer un articulo de este chevere FrameworkBootstrap, que no utilice desde inicios del año, la verdad no había tenido la necesidad (mas por falta de tiempo, por mi trabajo), pero bueno he estado viendo algunos recursos en la web, de los que de hecho hay un montón por ahí regados, pues encontré a una clase escrita en PHP, por Pak Xpertz, que es muy fácil de utilizar.

¿Que es Bootstrap?

Twitter Bootstrap es un framework o conjunto de herramientas de software libre para diseño de sitios y aplicaciones web. Contiene plantillas de diseño con tipografía, formularios, botones, cuadros, menús de navegación y otros elementos de diseño basado en HTML y CSS, así como, extensiones de JavaScript opcionales adicionales.

Bien ahora que sabemos que es Bootstrap, les explicare sobre esta clase. Esta clase te permite ingresar un conjunto de datos que deseas estructurar, en una tabla por ejemplo, pues esta clase dibujara la tabla en HTML, utilizando los estilos visuales del framework Bootstrap, con un encabezado que tu especificaras. ademas permite especificar si la tabla se pintara de manera alternada con esta función striped(), si deseas que se vean los bordes con bordered(), si deseas que aparezca un efecto hover que cuando el cursor se posicione en alguna fila esta se pinte hover(), y por ultimo si deseas que la tabla se vea con un estilo mas compacto pues se utiliza condensed(). También mencionar que este diseño es totalmente responsive, osea adaptativo, pero se controla también a través de código utilizando la función responsive(), si la colocas pues el diseño sera adaptativo, y si no pues sera estático. A esto mencionar que hice una modificación a esta clase añadiendo un segundo parámetro en la función addRow(), les explicare aquí

Empezamos a Trabajar

Primero creamos nuestra clase con este código, que solo modifique para que acepte un parámetro mas en la función addRow(), ahora acepta un segundo parámetro que es el estilo en contexto para pintar la fila de acuerdo a unos criterios que ustedes pueden especificar en su proyectos. mas info en la web de Bootstrap

<?php 

/**
* Helper class for generating bootstrap styled HTML table
* @access public
* @author Fayaz Khan <pakxpertz@gmail.com>
* @license http://www.gnu.org/licenses/gpl-3.0.en.html GPLv3
* @copyright (c) 2015, MaxTech Developers
****************** MODIFICADO *****************************
* POR Miguel Nurena para programacionx.net
***********************************************************
* @parametro opcional string $context para pintar fila utilizando
* las clases de bootstrap para las tablas
* 	opciones: class .active .success .warning .danger .info
***********************************************************
*/
class BootstrapTableHelper{

/**
* Table Columns holder
* @var array Array conatining columns
*/
private $columns = array();

/**
* Table rows holder
* @var array Multi-dimensional Array containing table data
*/
private $rows = array();

/**
* Table attributes holder (Classes etc)
* @var array
*/
private $attributes = array();

/**
* Makes table responsive or not
* @var boolean True means responsive false means not
*/
private $responsive = FALSE;

/**
* Construct table options
* @param string $id ID of this table
* @param array $attributes HTML Attributes for this table
*/
public function __construct($id = &quot;&quot;, $attributes = array()) {
if(!empty($id)){
$this->attributes[&quot;id&quot;] = $id;
}

if(!empty($attributes)){
foreach($attributes as $k => $v){
$this->attributes[$k] = $v;
}
}

$this->attributes[&quot;class&quot;][] = &quot;table&quot;;
}

/**
* Add table-hover css class to this table
* @return \BootstrapTableHelper
*/
public function hover(){
$this->attributes[&quot;class&quot;][] = &quot;table-hover&quot;;
return $this;
}

/**
* Add table-striped css class to this table
* @return \BootstrapTableHelper
*/
public function striped(){
$this->attributes[&quot;class&quot;][] = &quot;table-striped&quot;;
return $this;
}

/**
* Add table-bordered css class to this table
* Make this table's rows and columns bordered
* @return \BootstrapTableHelper
*/
public function bordered(){
$this->attributes["class"][] = "table-bordered";
return $this;
}

/**
* Make this table Responsive
* @return \BootstrapTableHelper
*/
public function responsive(){
$this->responsive = TRUE;
return $this;
}

/**
* Add condensed css class to this table
* @return \BootstrapTableHelper
*/
public function condensed(){
$this->attributes["class"][] = "table-condensed";
return $this;
}

/**
****************** MODIFICADO *****************************
* POR Miguel Nurena para programacionx.net
***********************************************************
* Add row of data to this table
* @param array $data Data in 1D array
* @parametro opcional string $context para pintar fila utilizando
* las clases de bootstrap para las tablas
* 	opciones: class .active .success .warning .danger .info
* @return \BootstrapTableHelper
*
*/
public function addRow($data = array(),$context = null){
$this->rows[] = array($data,$context);
return $this;
}

/**
* Add Columns (Table header/footer) to this table
* @param array $data Columns in 1D array
* @return \BootstrapTableHelper
*/
public function columns($data = array()){
$this->columns = $data;
return $this;
}

/**
* Add one column to the table
* @param string $column Coulmn name
* @return \BootstrapTableHelper
*/
public function addColumn($column){
$this->columns[] = $column;
return $this;
}

/**
* Construct Table
* @return string Returns HTML code of table
*/
public function __toString() {
return $this->make();
}

/**
* Generate HTML for this table and return it
* @return string Returns HTML Code of table
*/
public function make(){
$columns = "";
foreach($this->columns as $col){
$columns .= "$col";
}
$table = "";
$table .= ($this->responsive)?"</pre>
<div class="table-responsive">":""; $table .= "<table"; foreach($this->attributes as $name => $value){ if(is_array($value)){ $table .= " $name='"; foreach($value as $v){ $table .= " $v"; } $table .= "'"; }else{ $table .= " $name='$value'"; } } $table .= ">"; $table .= ""; $table .= $columns; $table .= ""; $table .= ""; foreach($this->rows as $row){ $table .= ''; foreach($row[0] as $column){ $table .= ''.$column.''; } $table .= ""; } $table .= ""; $table .= ""; $table .= $columns; $table .= ""; $table .= ""; $table .= ($this->responsive)?"</div><pre>":"";
return $table;
}
}

CONSTRUYENDO EL EJEMPLO: PHP

Aquí haremos nuestro ejemplo en PHP, realizando primero la llamada a la clase, luego creamos el objeto, después le asignamos los estilos visuales, ojo que es importante primero asignar los estilos para luego mandarle los datos,

<?php 
require 'class.BootstrapTable.php';
$table = new BootstrapTableHelper();
echo $table->bordered()
->striped()
->hover()
->columns(array("Languages","IDEs","Browsers","OSs"))
->addRow(array("PHP","NetBeans","FireFox","Windows"),"activ")
->addRow(array("PHP","NetBeans","FireFox","Windows"),"")
->addRow(array("PHP","NetBeans","FireFox","Windows"),"success")
->addRow(array("PHP","NetBeans","FireFox","Windows"))
->addRow(array("Java","Visual Studio","Chrome","Linux"),"warning")
->addRow(array("Java","Visual Studio","Chrome","Linux"))
->addRow(array("Java","Visual Studio","Chrome","Linux"),"danger")
->addRow(array("Java","Visual Studio","Chrome","Linux"),"")
->addRow(array("C++","Ecllips","Internet Explorer","Mac OS"),"info")
->addRow(array("C++","Ecllips","Internet Explorer","Mac OS"),"")
->addRow(array("C++","Ecllips","Internet Explorer","Mac OS"),"danger")
->addRow(array("C++","Ecllips","Internet Explorer","Mac OS"),"")
->make();
?>

CONSTRUYENDO EL EJEMPLO: HTML

Ahora tendremos que realizar las llamas a los archivos javascrip y CSS de bootstrap, sin esto no tendremos el estilo del framework que tan popular se ha vuelto entre los diseñadores. y pues añadiremos nuestro código PHP de arriba, con lo que tendremos este código:

<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags Bootstrap Table helper Example-->

<!-- Bootstrap --> 	


<!-- [if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<div class="container-fluid"></div>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

Bien eso es todo ahora solo es necesario copiar y realizar sus pruebas, para sus proyectos, ahora muchos se preguntaran en que ayudaría, pues en simplificar el trabajo de construir una tabla, así no tenga ningún estilo en especial, ya que te ayuda a reutilizar el código sin estar escribiendo nuevamente el código, les dejo una demo para que vean como se ve el código.

Gracias por leer el articulo, si te gusto compártelo con tus amigos en las diferentes redes sociales.

Shares