Passed
Push — master ( 468e47...0bebef )
by Jean-Christophe
02:09
created

DataTable::getUrls()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
495
	}
496
	
497
	public function onActiveRowChange($jsCode){
498
		$this->getHtmlComponent()->onActiveRowChange($jsCode);
499
		return $this;
500
	}
501
}
502