Passed
Push — master ( 399ae9...6e76cc )
by Jean-Christophe
01:59
created

DataTable::_generateRow()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 29
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 26
nc 5
nop 3
dl 0
loc 29
rs 8.5806
c 0
b 0
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
			$checked=false;
180
			if(isset($this->_checkedCallback)){
181
				$func=$this->_checkedCallback;
182
				$checked=$func($instance);
183
			}
184
			$ck->setChecked($checked);
185
			$ck->setOnChange("event.stopPropagation();");
186
			$field=$ck->getField();
187
			$field->setProperty("value",$dataAjax);
188
			$field->setProperty("name", "selection[]");
189
			if(isset($checkedClass))
190
				$field->setClass($checkedClass);
191
			\array_unshift($values, $ck);
192
		}
193
		$result=$table->newRow();
194
		$result->setIdentifier($this->identifier."-tr-".$id);
195
		$result->setProperty("data-ajax",$dataAjax);
196
		$result->setValues($values);
197
		$result->addToProperty("class",$this->_rowClass);
198
		return $result;
199
	}
200
201
	protected function _generatePagination($table,$js=NULL){
202
		if(isset($this->_toolbar)){
203
			if($this->_toolbarPosition==PositionInTable::FOOTER)
0 ignored issues
show
introduced by
The condition $this->_toolbarPosition ...PositionInTable::FOOTER can never be true.
Loading history...
204
				$this->_toolbar->setFloated("left");
205
		}
206
		$footer=$table->getFooter();
207
		$footer->mergeCol();
208
		$menu=new HtmlPaginationMenu("pagination-".$this->identifier,$this->_pagination->getPagesNumbers());
209
		$menu->floatRight();
210
		$menu->setActiveItem($this->_pagination->getPage()-1);
211
		$footer->addValues($menu);
212
		$this->_associatePaginationBehavior($menu,$js);
213
	}
214
215
	protected function _associatePaginationBehavior(HtmlMenu $menu,JsUtils $js=NULL){
216
		if(isset($this->_urls["refresh"])){
217
			$menu->postOnClick($this->_urls["refresh"],"{'p':$(this).attr('data-page')}",$this->getRefreshSelector(),["preventDefault"=>false,"jqueryDone"=>"replaceWith","hasLoader"=>false]);
218
		}
219
	}
220
221
	protected function _getFieldName($index){
222
		$fieldName=parent::_getFieldName($index);
223
		if(\is_object($fieldName))
224
			$fieldName="field-".$index;
225
		return $fieldName."[]";
226
	}
227
228
	protected function _getFieldCaption($index){
229
		return null;
230
	}
231
232
	protected function _setToolbarPosition($table,$captions=NULL){
233
		switch ($this->_toolbarPosition){
234
			case PositionInTable::BEFORETABLE:
235
			case PositionInTable::AFTERTABLE:
236
				if(isset($this->_compileParts)===false){
237
					$this->content[$this->_toolbarPosition]=$this->_toolbar;
238
				}
239
				break;
240
			case PositionInTable::HEADER:
241
			case PositionInTable::FOOTER:
242
			case PositionInTable::BODY:
243
				$this->addToolbarRow($this->_toolbarPosition,$table, $captions);
244
				break;
245
		}
246
	}
247
248
	/**
249
	 * Associates a $callback function after the compilation of the field at $index position
250
	 * The $callback function can take the following arguments : $field=>the compiled field, $instance : the active instance of the object, $index: the field position
251
	 * @param int $index postion of the compiled field
252
	 * @param callable $callback function called after the field compilation
253
	 * @return DataTable
254
	 */
255
	public function afterCompile($index,$callback){
256
		$this->_instanceViewer->afterCompile($index,$callback);
257
		return $this;
258
	}
259
260
	private function addToolbarRow($part,$table,$captions){
261
		$hasPart=$table->hasPart($part);
262
		if($hasPart){
263
			$row=$table->getPart($part)->addRow(\sizeof($captions));
264
		}else{
265
			$row=$table->getPart($part)->getRow(0);
266
		}
267
		$row->mergeCol();
268
		$row->setValues([$this->_toolbar]);
269
	}
270
271
	/**
272
	 * {@inheritDoc}
273
	 * @see Widget::getHtmlComponent()
274
	 * @return HtmlTable
275
	 */
276
	public function getHtmlComponent(){
277
		return $this->content["table"];
278
	}
279
280
	public function getUrls() {
281
		return $this->_urls;
282
	}
283
284
	/**
285
	 * Sets the associative array of urls for refreshing, updating or deleting
286
	 * think of defining the update zone with the setTargetSelector method
287
	 * @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
288
	 * @return DataTable
289
	 */
290
	public function setUrls($urls) {
291
		if(\is_array($urls)){
292
			$this->_urls["refresh"]=JArray::getValue($urls, "refresh",0);
293
			$this->_urls["edit"]=JArray::getValue($urls, "edit",1);
294
			$this->_urls["delete"]=JArray::getValue($urls, "delete",2);
295
		}else{
296
			$this->_urls=["refresh"=>$urls,"edit"=>$urls,"delete"=>$urls];
297
		}
298
		return $this;
299
	}
300
301
	/**
302
	 * Paginates the DataTable element with a Semantic HtmlPaginationMenu component
303
	 * @param number $page the active page number
304
	 * @param number $total_rowcount the total number of items
305
	 * @param number $items_per_page The number of items per page
306
	 * @param number $pages_visibles The number of visible pages in the Pagination component
307
	 * @return DataTable
308
	 */
309
	public function paginate($page,$total_rowcount,$items_per_page=10,$pages_visibles=null){
310
		$this->_pagination=new Pagination($items_per_page,$pages_visibles,$page,$total_rowcount);
311
		return $this;
312
	}
313
314
	/**
315
	 * Auto Paginates the DataTable element with a Semantic HtmlPaginationMenu component
316
	 * @param number $page the active page number
317
	 * @param number $items_per_page The number of items per page
318
	 * @param number $pages_visibles The number of visible pages in the Pagination component
319
	 * @return DataTable
320
	 */
321
	public function autoPaginate($page=1,$items_per_page=10,$pages_visibles=4){
322
		$this->_pagination=new Pagination($items_per_page,$pages_visibles,$page);
323
		return $this;
324
	}
325
326
327
328
	/**
329
	 * @param array $compileParts
330
	 * @return DataTable
331
	 */
332
	public function refresh($compileParts=["tbody"]){
333
		$this->_compileParts=$compileParts;
334
		return $this;
335
	}
336
337
338
	/**
339
	 * Adds a search input in toolbar
340
	 * @param string $position
341
	 * @return \Ajax\common\html\HtmlDoubleElement
342
	 */
343
	public function addSearchInToolbar($position=Direction::RIGHT){
344
		return $this->addInToolbar($this->getSearchField())->setPosition($position);
345
	}
346
347
	public function getSearchField(){
348
		if(isset($this->_searchField)===false){
349
			$this->_searchField=new HtmlInput("search-".$this->identifier,"search","","Search...");
350
			$this->_searchField->addIcon("search",Direction::RIGHT);
351
		}
352
		return $this->_searchField;
353
	}
354
355
	/**
356
	 * The callback function called after the insertion of each row when fromDatabaseObjects is called
357
	 * callback function takes the parameters $row : the row inserted and $object: the instance of model used
358
	 * @param callable $callback
359
	 * @return DataTable
360
	 */
361
	public function onNewRow($callback) {
362
		$this->content["table"]->onNewRow($callback);
363
		return $this;
364
	}
365
366
	/**
367
	 * Returns a form corresponding to the Datatable
368
	 * @return \Ajax\semantic\html\collections\form\HtmlForm
369
	 */
370
	public function asForm(){
371
		return $this->getForm();
372
	}
373
374
375
376
	protected function getTargetSelector($op) {
377
		$result=$this->_targetSelector;
378
		if(!isset($result[$op]))
379
			$result="#".$this->identifier;
380
		return $result[$op];
381
	}
382
383
	/**
384
	 * Sets the response element selector for Edit and Delete request with ajax
385
	 * @param string|array $_targetSelector string or associative array ["edit"=>"edit_selector","delete"=>"delete_selector"]
386
	 * @return DataTable
387
	 */
388
	public function setTargetSelector($_targetSelector) {
389
		if(!\is_array($_targetSelector)){
390
			$_targetSelector=["edit"=>$_targetSelector,"delete"=>$_targetSelector];
391
		}
392
		$this->_targetSelector=$_targetSelector;
393
		return $this;
394
	}
395
396
	public function getRefreshSelector() {
397
		if(isset($this->_refreshSelector))
398
			return $this->_refreshSelector;
399
		return "#".$this->identifier." tbody";
400
	}
401
402
	/**
403
	 * @param string $_refreshSelector
404
	 * @return DataTable
405
	 */
406
	public function setRefreshSelector($_refreshSelector) {
407
		$this->_refreshSelector=$_refreshSelector;
408
		return $this;
409
	}
410
411
	/**
412
	 * {@inheritDoc}
413
	 * @see \Ajax\common\Widget::show()
414
	 */
415
	public function show($modelInstance){
416
		if(\is_array($modelInstance)){
417
			if(isset($modelInstance[0]) && \is_array(array_values($modelInstance)[0]))
418
				$modelInstance=\json_decode(\json_encode($modelInstance), FALSE);
419
		}
420
		$this->_modelInstance=$modelInstance;
421
	}
422
423
	public function getRowClass() {
424
		return $this->_rowClass;
425
	}
426
427
	/**
428
	 * Sets the default row class (tr class)
429
	 * @param string $_rowClass
430
	 * @return DataTable
431
	 */
432
	public function setRowClass($_rowClass) {
433
		$this->_rowClass=$_rowClass;
434
		return $this;
435
	}
436
437
	/**
438
	 * Sets the message displayed when there is no record
439
	 * @param mixed $_emptyMessage
440
	 * @return DataTable
441
	 */
442
	public function setEmptyMessage($_emptyMessage) {
443
		$this->_emptyMessage=$_emptyMessage;
444
		return $this;
445
	}
446
447
	public function setSortable($colIndex=NULL) {
448
		$this->_sortable=$colIndex;
449
		return $this;
450
	}
451
452
	public function setActiveRowSelector($class="active",$event="click",$multiple=false){
453
		$this->_self->setActiveRowSelector($class,$event,$multiple);
454
		return $this;
455
	}
456
457
	public function hideColumn($colIndex){
458
		if(!\is_array($this->_hiddenColumns))
459
			$this->_hiddenColumns=[];
460
		$this->_hiddenColumns[]=$colIndex;
461
		return $this;
462
	}
463
464
	public function setColWidth($colIndex,$width){
465
		$this->_colWidths[$colIndex]=$width;
466
		return $this;
467
	}
468
	public function setColWidths($_colWidths) {
469
		$this->_colWidths = $_colWidths;
470
		return $this;
471
	}
472
473
	public function setColAlignment($colIndex,$alignment){
474
		$this->content["table"]->setColAlignment($colIndex,$alignment);
475
		return $this;
476
	}
477
}
478