Passed
Push — master ( ef609f...421c61 )
by Jean-Christophe
02:48
created

DataTable::compile()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 24
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 4
eloc 17
nc 5
nop 2
dl 0
loc 24
rs 8.6845
c 3
b 1
f 0
1
<?php
2
3
namespace Ajax\semantic\widgets\datatable;
4
5
use Ajax\common\Widget;
6
use Ajax\JsUtils;
7
use Ajax\semantic\html\collections\table\HtmlTable;
8
use Ajax\semantic\html\elements\HtmlInput;
9
use Ajax\semantic\html\collections\menus\HtmlPaginationMenu;
10
use Ajax\semantic\html\modules\checkbox\HtmlCheckbox;
11
use Ajax\semantic\html\base\constants\Direction;
12
use Ajax\service\JArray;
13
use Ajax\semantic\widgets\base\InstanceViewer;
14
use Ajax\semantic\html\collections\table\traits\TableTrait;
15
use Ajax\semantic\html\collections\HtmlMessage;
16
use Ajax\semantic\html\collections\menus\HtmlMenu;
17
use Ajax\semantic\html\base\traits\BaseTrait;
18
19
/**
20
 * DataTable widget for displaying list of objects
21
 * @version 1.0
22
 * @author jc
23
 * @since 2.2
24
 *
25
 */
26
class DataTable extends Widget {
27
	use TableTrait,DataTableFieldAsTrait,HasCheckboxesTrait,BaseTrait;
28
	protected $_searchField;
29
	protected $_urls;
30
	protected $_pagination;
31
	protected $_compileParts;
32
	protected $_deleteBehavior;
33
	protected $_editBehavior;
34
	protected $_visibleHover=false;
35
	protected $_targetSelector;
36
	protected $_refreshSelector;
37
	protected $_emptyMessage;
38
	protected $_json;
39
	protected $_rowClass="";
40
	protected $_sortable;
41
	protected $_hiddenColumns;
42
	protected $_colWidths;
43
44
45
	public function __construct($identifier,$model,$modelInstance=NULL) {
46
		parent::__construct($identifier, $model,$modelInstance);
47
		$this->_init(new InstanceViewer($identifier), "table", new HtmlTable($identifier, 0,0), false);
48
		$this->_urls=[];
49
		$this->_emptyMessage=new HtmlMessage("","nothing to display");
50
		$this->_emptyMessage->setIcon("info circle");
51
	}
52
53
	public function run(JsUtils $js){
54
		if($this->_hasCheckboxes && isset($js)){
55
			$this->_runCheckboxes($js);
56
		}
57
		if($this->_visibleHover){
58
			$js->execOn("mouseover", "#".$this->identifier." tr", "$(event.target).closest('tr').find('.visibleover').css('visibility', 'visible');",["preventDefault"=>false,"stopPropagation"=>true]);
59
			$js->execOn("mouseout", "#".$this->identifier." tr", "$(event.target).closest('tr').find('.visibleover').css('visibility', 'hidden');",["preventDefault"=>false,"stopPropagation"=>true]);
60
		}
61
		if(\is_array($this->_deleteBehavior))
62
			$this->_generateBehavior("delete",$this->_deleteBehavior, $js);
63
		if(\is_array($this->_editBehavior))
64
			$this->_generateBehavior("edit",$this->_editBehavior,$js);
65
		return parent::run($js);
66
	}
67
68
69
70
	protected function _generateBehavior($op,$params,JsUtils $js){
71
		if(isset($this->_urls[$op])){
72
			$params=\array_merge($params,["attr"=>"data-ajax"]);
73
			$js->ajaxOnClick("#".$this->identifier." ._".$op, $this->_urls[$op],$this->getTargetSelector($op),$params);
74
		}
75
	}
76
77
	/**
78
	 * {@inheritDoc}
79
	 * @see \Ajax\semantic\html\collections\table\TableTrait::getTable()
80
	 */
81
	protected function getTable() {
82
		return $this->content["table"];
83
	}
84
85
86
	public function compile(JsUtils $js=NULL,&$view=NULL){
87
		if(!$this->_generated){
88
			$this->_instanceViewer->setInstance($this->_model);
89
			$captions=$this->_instanceViewer->getCaptions();
90
			$table=$this->content["table"];
91
			if($this->_hasCheckboxes){
92
				$this->_generateMainCheckbox($captions);
93
			}
94
			$table->setRowCount(0, \sizeof($captions));
95
			$this->_generateHeader($table,$captions);
96
97
			if(isset($this->_compileParts))
98
				$table->setCompileParts($this->_compileParts);
99
100
			$this->_generateContent($table);
101
102
			$this->compileExtraElements($table, $captions,$js);
103
104
			$this->content=JArray::sortAssociative($this->content, [PositionInTable::BEFORETABLE,"table",PositionInTable::AFTERTABLE]);
105
			$this->_compileForm();
106
			$this->_applyStyleAttributes($table);
107
			$this->_generated=true;
108
		}
109
		return parent::compile($js,$view);
110
	}
111
112
	protected function compileExtraElements($table,$captions,JsUtils $js=NULL){
113
		if(isset($this->_searchField) && isset($js) && isset($this->_urls["refresh"])){
114
				$this->_searchField->postOn("change", $this->_urls["refresh"],"{'s':$(this).val()}","#".$this->identifier." tbody",["preventDefault"=>false,"jqueryDone"=>"replaceWith"]);
115
		}
116
		if($this->_hasCheckboxes && $table->hasPart("thead")){
117
			$table->getHeader()->getCell(0, 0)->addClass("no-sort");
118
		}
119
120
		if(isset($this->_toolbar)){
121
			$this->_setToolbarPosition($table, $captions);
122
		}
123
		if(isset($this->_pagination) && $this->_pagination->getVisible()){
124
			$this->_generatePagination($table,$js);
125
		}
126
	}
127
128
	protected function _applyStyleAttributes($table){
129
		if(isset($this->_hiddenColumns))
130
			$this->_hideColumns();
131
			if(isset($this->_colWidths)){
132
				foreach ($this->_colWidths as $colIndex=>$width){
133
					$table->setColWidth($colIndex,$width);
134
				}
135
			}
136
	}
137
138
	protected function _hideColumns(){
139
		foreach ($this->_hiddenColumns as $colIndex){
140
			$this->_self->hideColumn($colIndex);
141
		}
142
		return $this;
143
	}
144
145
	protected function _generateHeader(HtmlTable $table,$captions){
146
		$table->setHeaderValues($captions);
147
		if(isset($this->_sortable)){
148
			$table->setSortable($this->_sortable);
149
		}
150
	}
151
152
153
154
	protected function _generateContent($table){
155
		$objects=$this->_modelInstance;
156
		if(isset($this->_pagination)){
157
			$objects=$this->_pagination->getObjects($this->_modelInstance);
158
		}
159
			InstanceViewer::setIndex(0);
160
			$table->fromDatabaseObjects($objects, function($instance) use($table){
161
				return $this->_generateRow($instance, $table);
162
			});
163
		if($table->getRowCount()==0){
164
			$result=$table->addRow();
165
			$result->mergeRow();
166
			$result->setValues([$this->_emptyMessage]);
167
		}
168
	}
169
170
	protected function _generateRow($instance,&$table,$checkedClass=null){
171
		$this->_instanceViewer->setInstance($instance);
172
		InstanceViewer::$index++;
173
		$values= $this->_instanceViewer->getValues();
174
		$id=$this->_instanceViewer->getIdentifier();
175
		$dataAjax=$id;
176
		$id=$this->cleanIdentifier($id);
177
		if($this->_hasCheckboxes){
178
			$ck=new HtmlCheckbox("ck-".$this->identifier."-".$id,"");
179
			$ck->setOnChange("event.stopPropagation();");
180
			$field=$ck->getField();
181
			$field->setProperty("value",$dataAjax);
182
			$field->setProperty("name", "selection[]");
183
			if(isset($checkedClass))
184
				$field->setClass($checkedClass);
185
			\array_unshift($values, $ck);
186
		}
187
		$result=$table->newRow();
188
		$result->setIdentifier($this->identifier."-tr-".$id);
189
		$result->setProperty("data-ajax",$dataAjax);
190
		$result->setValues($values);
191
		$result->addToProperty("class",$this->_rowClass);
192
		return $result;
193
	}
194
195
	protected function _generatePagination($table,$js=NULL){
196
		if(isset($this->_toolbar)){
197
			if($this->_toolbarPosition==PositionInTable::FOOTER)
198
				$this->_toolbar->setFloated("left");
199
		}
200
		$footer=$table->getFooter();
201
		$footer->mergeCol();
202
		$menu=new HtmlPaginationMenu("pagination-".$this->identifier,$this->_pagination->getPagesNumbers());
203
		$menu->floatRight();
204
		$menu->setActiveItem($this->_pagination->getPage()-1);
205
		$footer->addValues($menu);
206
		$this->_associatePaginationBehavior($menu,$js);
207
	}
208
209
	protected function _associatePaginationBehavior(HtmlMenu $menu,JsUtils $js=NULL){
210
		if(isset($this->_urls["refresh"])){
211
			$menu->postOnClick($this->_urls["refresh"],"{'p':$(this).attr('data-page')}",$this->getRefreshSelector(),["preventDefault"=>false,"jqueryDone"=>"replaceWith","hasLoader"=>false]);
212
		}
213
	}
214
215
	protected function _getFieldName($index){
216
		$fieldName=parent::_getFieldName($index);
217
		if(\is_object($fieldName))
218
			$fieldName="field-".$index;
219
		return $fieldName."[]";
220
	}
221
222
	protected function _getFieldCaption($index){
223
		return null;
224
	}
225
226
	protected function _setToolbarPosition($table,$captions=NULL){
227
		switch ($this->_toolbarPosition){
228
			case PositionInTable::BEFORETABLE:
229
			case PositionInTable::AFTERTABLE:
230
				if(isset($this->_compileParts)===false){
231
					$this->content[$this->_toolbarPosition]=$this->_toolbar;
232
				}
233
				break;
234
			case PositionInTable::HEADER:
235
			case PositionInTable::FOOTER:
236
			case PositionInTable::BODY:
237
				$this->addToolbarRow($this->_toolbarPosition,$table, $captions);
238
				break;
239
		}
240
	}
241
242
	/**
243
	 * Associates a $callback function after the compilation of the field at $index position
244
	 * The $callback function can take the following arguments : $field=>the compiled field, $instance : the active instance of the object, $index: the field position
245
	 * @param int $index postion of the compiled field
246
	 * @param callable $callback function called after the field compilation
247
	 * @return DataTable
248
	 */
249
	public function afterCompile($index,$callback){
250
		$this->_instanceViewer->afterCompile($index,$callback);
251
		return $this;
252
	}
253
254
	private function addToolbarRow($part,$table,$captions){
255
		$hasPart=$table->hasPart($part);
256
		if($hasPart){
257
			$row=$table->getPart($part)->addRow(\sizeof($captions));
258
		}else{
259
			$row=$table->getPart($part)->getRow(0);
260
		}
261
		$row->mergeCol();
262
		$row->setValues([$this->_toolbar]);
263
	}
264
265
	/**
266
	 * {@inheritDoc}
267
	 * @see Widget::getHtmlComponent()
268
	 * @return HtmlTable
269
	 */
270
	public function getHtmlComponent(){
271
		return $this->content["table"];
272
	}
273
274
	public function getUrls() {
275
		return $this->_urls;
276
	}
277
278
	/**
279
	 * Sets the associative array of urls for refreshing, updating or deleting
280
	 * think of defining the update zone with the setTargetSelector method
281
	 * @param string|array $urls associative array with keys refresh: for refreshing with search field or pagination, edit : for updating a row, delete: for deleting a row
282
	 * @return DataTable
283
	 */
284
	public function setUrls($urls) {
285
		if(\is_array($urls)){
286
			$this->_urls["refresh"]=JArray::getValue($urls, "refresh",0);
287
			$this->_urls["edit"]=JArray::getValue($urls, "edit",1);
288
			$this->_urls["delete"]=JArray::getValue($urls, "delete",2);
289
		}else{
290
			$this->_urls=["refresh"=>$urls,"edit"=>$urls,"delete"=>$urls];
291
		}
292
		return $this;
293
	}
294
295
	/**
296
	 * Paginates the DataTable element with a Semantic HtmlPaginationMenu component
297
	 * @param number $page the active page number
298
	 * @param number $total_rowcount the total number of items
299
	 * @param number $items_per_page The number of items per page
300
	 * @param number $pages_visibles The number of visible pages in the Pagination component
301
	 * @return DataTable
302
	 */
303
	public function paginate($page,$total_rowcount,$items_per_page=10,$pages_visibles=null){
304
		$this->_pagination=new Pagination($items_per_page,$pages_visibles,$page,$total_rowcount);
305
		return $this;
306
	}
307
308
	/**
309
	 * Auto Paginates the DataTable element with a Semantic HtmlPaginationMenu component
310
	 * @param number $page the active page number
311
	 * @param number $items_per_page The number of items per page
312
	 * @param number $pages_visibles The number of visible pages in the Pagination component
313
	 * @return DataTable
314
	 */
315
	public function autoPaginate($page=1,$items_per_page=10,$pages_visibles=4){
316
		$this->_pagination=new Pagination($items_per_page,$pages_visibles,$page);
317
		return $this;
318
	}
319
320
321
322
	/**
323
	 * @param array $compileParts
324
	 * @return DataTable
325
	 */
326
	public function refresh($compileParts=["tbody"]){
327
		$this->_compileParts=$compileParts;
328
		return $this;
329
	}
330
331
332
	/**
333
	 * Adds a search input in toolbar
334
	 * @param string $position
335
	 * @return \Ajax\common\html\HtmlDoubleElement
336
	 */
337
	public function addSearchInToolbar($position=Direction::RIGHT){
338
		return $this->addInToolbar($this->getSearchField())->setPosition($position);
339
	}
340
341
	public function getSearchField(){
342
		if(isset($this->_searchField)===false){
343
			$this->_searchField=new HtmlInput("search-".$this->identifier,"search","","Search...");
344
			$this->_searchField->addIcon("search",Direction::RIGHT);
345
		}
346
		return $this->_searchField;
347
	}
348
349
	/**
350
	 * The callback function called after the insertion of each row when fromDatabaseObjects is called
351
	 * callback function takes the parameters $row : the row inserted and $object: the instance of model used
352
	 * @param callable $callback
353
	 * @return DataTable
354
	 */
355
	public function onNewRow($callback) {
356
		$this->content["table"]->onNewRow($callback);
357
		return $this;
358
	}
359
360
	/**
361
	 * Returns a form corresponding to the Datatable
362
	 * @return \Ajax\semantic\html\collections\form\HtmlForm
363
	 */
364
	public function asForm(){
365
		return $this->getForm();
366
	}
367
368
369
370
	protected function getTargetSelector($op) {
371
		$result=$this->_targetSelector;
372
		if(!isset($result[$op]))
373
			$result="#".$this->identifier;
374
		return $result[$op];
375
	}
376
377
	/**
378
	 * Sets the response element selector for Edit and Delete request with ajax
379
	 * @param string|array $_targetSelector string or associative array ["edit"=>"edit_selector","delete"=>"delete_selector"]
380
	 * @return DataTable
381
	 */
382
	public function setTargetSelector($_targetSelector) {
383
		if(!\is_array($_targetSelector)){
384
			$_targetSelector=["edit"=>$_targetSelector,"delete"=>$_targetSelector];
385
		}
386
		$this->_targetSelector=$_targetSelector;
387
		return $this;
388
	}
389
390
	public function getRefreshSelector() {
391
		if(isset($this->_refreshSelector))
392
			return $this->_refreshSelector;
393
		return "#".$this->identifier." tbody";
394
	}
395
396
	/**
397
	 * @param string $_refreshSelector
398
	 * @return DataTable
399
	 */
400
	public function setRefreshSelector($_refreshSelector) {
401
		$this->_refreshSelector=$_refreshSelector;
402
		return $this;
403
	}
404
405
	/**
406
	 * {@inheritDoc}
407
	 * @see \Ajax\common\Widget::show()
408
	 */
409
	public function show($modelInstance){
410
		if(\is_array($modelInstance)){
411
			if(isset($modelInstance[0]) && \is_array(array_values($modelInstance)[0]))
412
				$modelInstance=\json_decode(\json_encode($modelInstance), FALSE);
413
		}
414
		$this->_modelInstance=$modelInstance;
415
	}
416
417
	public function getRowClass() {
418
		return $this->_rowClass;
419
	}
420
421
	/**
422
	 * Sets the default row class (tr class)
423
	 * @param string $_rowClass
424
	 * @return DataTable
425
	 */
426
	public function setRowClass($_rowClass) {
427
		$this->_rowClass=$_rowClass;
428
		return $this;
429
	}
430
431
	/**
432
	 * Sets the message displayed when there is no record
433
	 * @param mixed $_emptyMessage
434
	 * @return DataTable
435
	 */
436
	public function setEmptyMessage($_emptyMessage) {
437
		$this->_emptyMessage=$_emptyMessage;
438
		return $this;
439
	}
440
441
	public function setSortable($colIndex=NULL) {
442
		$this->_sortable=$colIndex;
443
		return $this;
444
	}
445
446
	public function setActiveRowSelector($class="active",$event="click",$multiple=false){
447
		$this->_self->setActiveRowSelector($class,$event,$multiple);
448
		return $this;
449
	}
450
451
	public function hideColumn($colIndex){
452
		if(!\is_array($this->_hiddenColumns))
453
			$this->_hiddenColumns=[];
454
		$this->_hiddenColumns[]=$colIndex;
455
		return $this;
456
	}
457
458
	public function setColWidth($colIndex,$width){
459
		$this->_colWidths[$colIndex]=$width;
460
		return $this;
461
	}
462
	public function setColWidths($_colWidths) {
463
		$this->_colWidths = $_colWidths;
464
		return $this;
465
	}
466
467
	public function setColAlignment($colIndex,$alignment){
468
		$this->content["table"]->setColAlignment($colIndex,$alignment);
469
		return $this;
470
	}
471
}
472