Back to home page
Il Jester
My little dream is in developing

DM Table

DM Table non è un vero e proprio plugin, ma una classe per creare tabelle. È un generatore di tabelle, personalizzabile e adatto a qualsiasi progetto PHP. Essendo una classe generica, è cross-script, quindi può essere adattata e utilizzata su diversi tipi di piattaforma di contenuto (CMS). Il pacchetto include però anche DM_Table_WP, che è una classe preparata appositamente per WordPress e Classicpress. DM_Table WP non è un’estensione di DM_Table, ma utilizza un’istanza DM_Table. Nota preliminare: tutti i valori del passato dovrebbero essere disinfettati e sfuggiti

DM_Table uso base

Innanzitutto è necessario stabilire dove si trova la classe. Usiamo require o meglio require_once:

require_once dirname(__DIR__) . '/dm-table/classes/class-dm-table.php';

Creiamo l’istanza:

$instance = new Dm_Table;

Base url

Definiamo l’url di base, e cioè il collegamento che punta al nostro file dove abbiamo istanziato la classe o è localizzata la vostra tabella.

$instance->setBaseUrl( $url = '' );
$your_url = 'http://mysite/example.php'; // The url where the table script is located 
$instance->setBaseUrl( $your_url );

Ordinamento

Impostiamo la selezione ordinabile, in base ai valori, se lo desideri:

$instance->setSortable( $args = array(),  $input = null, $submit = null );
$instance->setSortable(
	array(
          'orderby' => array( 'orderby', 'ID' ),        // values are: action name and default value
          'order'   => array( 'order', 'asc', 'desc' )  // values are: action name, default value and alt value
	),
	DM_Table::input(
	  'select',
          array(
		'name'  => 'orderby',                                      // name of action
		'value' => DM_Table::action( INPUT_GET, 'orderby', '-1' ), // you can use $_GET['orderby'] or filter_input( INPUT GET, 'orderby' )
		'choices' => array(
			'ID' 	    => 'ID',
			'email'     => 'Email',
			'username'  => 'Username'
		)
	   )
	),
	DM_Table::input(
		'submit',
		array(
			'value' => 'Order'
		)
	)
);

Cerca

Per costruire un’azione di ricerca.

$instance->setSearch( $args = array(), $input = null, $submit = null );

Per sortable valgono le stesse spiegazioni, con le dovute differenze nell’esempio, in particolare per quanto riguarda $args dove viene passato un solo argomento con un array come valore.

$instance->setSearch(
	array(
		'search' => array( 'search_action', '' ) // values are: action name and default value
	),
	DM_Table::input(
		'search',
		array(
			'name'  => 'search_action', // name of action
			'value' => DM_Table::action( INPUT_GET, 'search_action', '' ), // you can use $_GET['search_action'] or filter_input( INPUT GET, 'search_action' )
			'id'    => 'mysearch_id',
			'class' => 'mysearch_class',
			'placeholder' => 'Find...'
		)
	),
	DM_Table::input(
		'submit',
		array(
			'value' => 'Search'
		)
	)
);

Filters

Con i filtri otteniamo risultati in base alle condizioni stabilite.

$instance->setFilters( $inputs = array(), $submit = null );

I filtri possono essere più di uno. Per questo motivo, il primo argomento di setFilters sarà un array di input. Come esempio. Tieni presente che l’argomento $args viene spostato nell’array input. Nell’esempio abbiamo due filtri: per “colore” e per “città”.

Importante, i tasti “filtro” e “input” devono essere chiamati veri e propri “filtro” e “input”!:

$instance->setFilters(
	array(
		'color' => array(
			'filter' => array( 'color', '-1' ), // values are: action name and default value (ex $args argument)
			'input' => DM_Table::input(
				'select',
				array(
					'name' => 'color', // name of action
					'value' => DM_Table::action( INPUT_GET, 'color', '-1' ), // you can use $_GET['color'] or filter_input( INPUT GET, 'color' )
					'choices' => array(
						'-1' 		=> 'Color Filter',
						'red'  		=> 'Red',
						'yellow'  	=> 'Yellow',
						'blue'  	=> 'Blu',
						'white' 	=> 'White'
					)
				)
			)
		),
		'city' => array(
			'filter' => array( 'city', '-1' ), // values are: action name and default value
			'input' => DM_Table::input(
				'select',
				array(
					'name' => 'city', // name of action
					'value' => DM_Table::action( INPUT_GET, 'city', '-1' ), // you can use $_GET['city'] or filter_input( INPUT GET, 'city' )
					'choices' => array(
						'-1' 		=> 'City Filter',
						'rome'  		=> 'Rome',
						'paris'			=> 'Paris',
						'london'		=> 'London',
						'new_york'		=> 'New York'
					)
				)
			)
		)
	),
	DM_Table::input(
		'submit',
		array(
			'value' => 'Filter'
		)
	)
);

Azioni

Nella tabella, abbiamo bisogno di una selezione per le azioni. Eccolo!

$instance->setActions( $args = array(), $input = null, $submit = null

Si applicano le stesse spiegazioni fornite per ordinabile.

$instance->setActions(
	array(
		'action' => array( 'select_action', '-1' ) // values are: action name and default value
	),
	DM_Table::input(
		'select',
		array(
			'name'  => 'select_action', // name of action
			'value' => DM_Table::action( INPUT_GET, 'select_action', '-1' ), // you can use $_GET['select_action'] or filter_input( INPUT GET, 'select_action' )
			'choices' => array(
				'-1' 		=> 'Actions',
				'delete' 	=> 'Delete',
				'edit' 		=> 'Edit'
			),
		)
	),
	DM_Table::input(
		'submit',
		array(
			'value' => 'Action'
		)
	)
);

Perpage

Ciò è necessario per scegliere il limite di elementi per pagina. Questo, se hai una quantità enorme di dati da visualizzare nella tabella.

$instance->setPerpage( $args = array(), $input = null, $submit = null );

Come potete vedere il metodo è lo stesso di quelli già visti.

$instance->setPerpage(
	array(
		'perpage' => array( 'perpage', 5 ), // name of action and default value
	),
	DM_Table::input(
		'text',
		array(
			'name' => 'perpage', // name of action
			'value'	=> DM_Table::action( INPUT_GET, 'perpage', 5 ), // you can use $_GET['perpage'] or filter_input( INPUT GET, 'perpage' )
			'class' => 'dm-perpage'
		)
	),
	DM_Table::input(
		'submit',
		array(
			'value' => 'Perpage'
		)
	)
);

Prepariamo i dati

Ora dobbiamo preparare la nostra query, filtrare, agire e/o ordinare i dati in base alle selezioni viste sopra. DM_Table ci offre diverse proprietà pubbliche per fare questo:
$instance->orderby;  // order by value
$instance->order;    // order ASC or DESC
$instance->search;   // fiter by search key
$instance->filters;  // an array of filters
   // eg. $instance->filters['color']['value'] // for color filter
   // eg. $instance->filters['city']['value']  // for city filter
$instance->action;            // action selected
$instance->input_action_name; // This property refers to the name of the reconstructed action starting from the property $instance-> action, accompanied by square brackets to trap multiple values.
$instance->perpage;           // how many items will be displayed in the table in each page. For usage, see below

Dopo aver filtrato la nostra query, con il risultato dobbiamo preparare il paging. In questo modo otterremo anche i valori di impaginazione (offset e limit) che verranno applicati alla nostra query.

$instance->setPagination( $args  = array() );
$instance->setPagination(
	array(
		'total_rows'   => $query_rows,                              // total number of your query rows after filtering. Argument accept array or int
		'start'        => array( 'tpage', 1 ),                      // name of page and start value
		'limit'        => array( 'tperpage', $instance->perpage ),  // name of perpage and the value obtained from select perpage
		'action_uri'   => true                                      // set true to use base_url for action pagination
	)
);

A questo punto recuperiamo le proprietà pubbliche di limit e offset:

$offset  = $instance->offset;
$limit   = $instance->limit; // aka perpage
Nota. Come emerge, abbiamo due proprietà che hanno un valore simile: $instance->perpage e $instance->limit. In effetti sono intercambiabili. Il primo è stato progettato per comodità, perché è il risultato dell’azione perpage e imposterebbe “limit” in setPerpage, per ottenere $instance->limit. A questo punto possiamo concludere il filtraggio della nostra query con le proprietà $limit e $offset. I risultati verranno utilizzati per creare una tabella dati.

Colonne

Prima creiamo colonne. È molto semplice. È un array:
$columns = array(
   'action'   => '',        // we use this column for actions
   'ID'       => 'ID',      // column for IDs of item
   'username' => 'Username', // column for usernames
   'email     => 'Email'    // column for emails
);

Dati della tabella

Il risultato della query può essere un array di oggetti da estrarre con un ciclo while o foreach.
$data = array();
$users = $our_query; // In the example the query concerns a user table, composed of an array of IDs, usernames and emails.
if( !empty( $users ) ) {
    foreach( $users as $key => $user ) { // or while( $row = $users->fetch_assoc() )
	
	$data[] = array(
		'action' => DM_Table::input( 'checkbox', // this is an action for manage delete or edit row
			array(
				'name'  	=> $instance->input_action_name, // See below for description
				'value' 	=> $user['ID'],
				'class' 	=> $instance->action, // see below for description
				'id'	   	=> ( $instance->action !== '' ? $instance->action . '-' . $user['ID'] : '' )
			)
		),
		'ID' 		=> $user['ID'],
		'username' 	=> $user['username'],
		'email' 	=> $user['email']
	);

   }

}

Set Tabella

Ora abbiamo tutti gli elementi per allestire la tavola.
$instance->setTable( $args = array() );
$args = array(
	'header' 		=> $columns,     // columns
	'content' 		=> $data,        // data,
	'footer'		=> true,	 // if true, we render footer as mirror header
	'raw_data'		=> $users,	 // the array of users example
	'no_data'		=> 'Sorry, no data yet!', // message for no results
	'sortable'		=> true, 	 // if yes, columns will be sortable
	'table_fixed'	        => true,	 // if yes table will be render fixed
	'table_id'		=> 'test_id',    // id for table,
	'before_list'	=> array( // create a menu before the list (available also after_list)
		'<a href="' . DM_Table::escValue( $your_url ) . '">Base</a>',
		DM_Table::SEP,
		'<span class="total-rows">Total Items: ' .DM_Table::escValue( $dm_table->total_rows ) . '</span>',
		DM_Table::SEP,
		'Other stuff!'
	),
	'scope_row' 		=> 'action', // for usability
	'column_bulk'		=> 'action', // set column bulk (remember in columns?)
	'bulk_js_callback'	=> 'toggleBulk(this)' // action js for bulk. Set false if you want to create your own.
);

$instance->setTable( $args );

La tabella è completa dei requisiti minimi. Per visualizzarlo:

$instance->displayTable();

Inserisci riga (opzionale)

Se lo desideri, puoi inserire una riga interna nella tabella. Utilizzando questo metodo, dopo DM_Table::setTable():

$instance->innerRow( $after_row = int, $class = '', $callback( $columns, $instance, $data ) );
$dm_table->innerRow( 2, 'inner-row-2', function( $columns, $instance, $users ) {  // we wont insert a row after second table row
	$user_name = $users[1]['username'];
	return '<td class="hidden-row" style="display:none; background-color: red;" colspan="' . DM_Table::escValue( $columns ) . '">This is a innered row for ' . DM_Table::escValue( $user_name ) . '</td>';
} );

Conclusions

Per maggiori dettagli, personalizzazioni, argomenti o valori passabili e molto altro, vedere la classe DM_Table. Per WordPress è disponibile nel pacchetto la classe DM_Table_WP.   Download   Donate