Mokuji /www/app/AdminModule/components/Datagrid/DataGrid.php

Language PHP Lines 1205
MD5 Hash 2bcc4fa0fcfe25280c1bc5ffc32a408d
Repository https://github.com/bazo/Mokuji.git View Raw File View Project SPDX
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
<?php

/**
 * This source file is subject to the "New BSD License".
 *
 * For more information please see http://nettephp.com
 *
 * @author     Roman Sklenář
 * @copyright  Copyright (c) 2009 Roman Sklenář (http://romansklenar.cz)
 * @license    New BSD License
 * @link       http://nettephp.com/extras/datagrid
 */



/**
 * A data bound list control that displays the items from data source in a table.
 * The DataGrid control allows you to select, sort, and manage these items.
 *
 * <code>
 * $grid = new DataGrid;
 * $grid->bindDataTable($model->findAll($model->table)->toDataSource());
 *
 * $grid->addColumn('column', 'Column caption')->addFilter();
 * $grid['column']->getCellPrototype()->style('text-align: center');
 *
 * $grid->addActionColumn('Actions');
 * $grid->addAction('Edit', 'Item:edit');
 *
 * $presenter->addComponent($grid, 'componentName');
 * </code>
 *
 * @author     Roman Sklenář
 * @copyright  Copyright (c) 2009 Roman Sklenář (http://romansklenar.cz)
 * @license    New BSD License
 * @example    http://nettephp.com/extras/datagrid
 * @package    Nette\Extras\DataGrid
 * @version    $Id$
 */
class DataGrid extends Control implements ArrayAccess, INamingContainer
{
	/** @persistent int */
	public $page = 1;

	/** @persistent string */
	public $order = '';

	/** @persistent string */
	public $filters = '';

	/** @persistent int */
	public $itemsPerPage = 15;

	/** @var array */
	public $displayedItems = array('all', 5, 10, 15, 20, 50, 100);

	/** @var bool  multi column order */
	public $multiOrder = TRUE;

	/** @var bool  disables ordering for all columns */
	public $disableOrder = FALSE;

	/** @var string */
	public $defaultOrder;

	/** @var string */
	public $defaultFilters;

	/** @var array */
	public $operations = array();

	/** @var array  of valid callback(s) */
	protected $onOperationSubmit;

	/** @var bool  can datagrid save his state into session? */
	public $rememberState = FALSE;

	/** @var int|string  session timeout (default: until is browser closed) */
	public $timeout = 0;

	/** @var IDataGridRenderer */
	protected $renderer;

	/** @var DibiDataSource */
	protected $dataSource;

	/** @var Paginator */
	protected $paginator;

	/** @var string */
	public $keyName;

	/** @var string */
	protected $receivedSignal;

	/** @var ActionColumn */
	protected $currentActionColumn;

	/** @var bool  was method render() called? */
	protected $wasRendered = FALSE;

	/** @var ITranslator */
	protected $translator;


	/**
	 * Data grid constructor.
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct(); // intentionally without any arguments (because of session loadState)
		$this->paginator = new Paginator;
                $this->paginator->itemsPerPage = 10;
		$session = $this->getSession();
		if (!$session->isStarted()) {
			$session->start();
		}
	}


	/**
	 * Binds data source to data grid.
	 * @param  DibiDataSource
	 * @throws DibiException
	 * @return void
	 */
	public function bindDataTable(DibiDataSource $dataSource)
	{
		$this->dataSource = $dataSource;
		$this->paginator->itemCount = count($dataSource);
	}


	/**
	 * Getter / property method.
	 * @return DibiDataSource
	 */
	public function getDataSource()
	{
		return $this->dataSource;
	}



	/********************* public getters and setters *********************/



	/**
	 * Getter / property method.
	 * Generates list of pages used for visual control. Use for your custom paginator rendering.
	 * @return array
	 */
	public function getSteps($count = 15)
	{
		// paginator steps
		$arr = range(max($this->paginator->firstPage, $this->page - 3), min($this->paginator->lastPage, $this->page + 3));
		$quotient = ($this->paginator->pageCount - 1) / $count;
		for ($i = 0; $i <= $count; $i++) {
			$arr[] = round($quotient * $i) + $this->paginator->firstPage;
		}
		sort($arr);

		return array_values(array_unique($arr));
	}


	/**
	 * Getter / property method.
	 * @return Paginator
	 */
	public function getPaginator()
	{
		return $this->paginator;
	}


	/**
	 * Setter / property method.
	 * @param  mixed  callback(s) to handler(s) which is called after data grid form operation is submited.
	 * @return void
	 */
	public function setOnOperationSubmit($callback)
	{
		if (!is_array($this->onOperationSubmit)) {
			$this->onOperationSubmit = array();
		}
		$this->onOperationSubmit[] = $callback;
	}


	/**
	 * Getter / property method.
	 * @return array
	 */
	public function getOnOperationSubmit()
	{
		return $this->onOperationSubmit;
	}



	/********************* Iterators getters *********************/



	/**
	 * Iterates over datagrid rows.
	 * @throws InvalidStateException
	 * @return DibiResultIterator
	 */
	public function getRows()
	{
		if (!$this->dataSource instanceof DibiDataSource) {
			throw new InvalidStateException("Data source has not been set or has invalid data type. You must set data source before you want get rows.");
		}
		return $this->dataSource->getIterator();
	}


	/**
	 * Iterates over datagrid columns.
	 * @param  string
	 * @throws InvalidArgumentException
	 * @return ArrayIterator
	 */
	public function getColumns($type = 'IDataGridColumn')
	{
		$columns = new ArrayObject();
		foreach ($this->getComponents(FALSE, $type) as $column) {
			$columns->append($column);
		}
		return $columns->getIterator();
	}


	/**
	 * Iterates over datagrid filters.
	 * @param  string
	 * @throws InvalidArgumentException
	 * @return ArrayIterator
	 */
	public function getFilters($type = 'IDataGridColumnFilter')
	{
		$filters = new ArrayObject();
		foreach ($this->getColumns() as $column) {
			if ($column->hasFilter()) {
				$filter = $column->getFilter();
				if ($filter instanceof $type) {
					$filters->append($column->getFilter());
				}
			}
		}
		return $filters->getIterator();
	}


	/**
	 * TODO: throw new DeprecatedException
	 * Iterates over all datagrid actions.
	 * @param  string
	 * @throws InvalidArgumentException
	 * @return ArrayIterator
	 */
	public function getActions($type = 'IDataGridAction')
	{
		$actions = new ArrayObject();
		foreach ($this->getColumns('ActionColumn') as $column) {
			if ($column->hasAction()) {
				foreach ($column->getActions() as $action) {
					if ($action instanceof $type) {
						$actions->append($action);
					}
				}
			}
		}
		return $actions->getIterator();
	}



	/********************* general data grid behavior *********************/



	/**
	 * Does data grid has any row?
	 * @return bool
	 */
	public function hasRows()
	{
		return count($this->getRows()) > 0;
	}


	/**
	 * Does data grid has any column?
	 * @param  string
	 * @return bool
	 */
	public function hasColumns($type = NULL)
	{
		return count($type == NULL ? $this->getColumns() : $this->getColumns($type)) > 0;
	}


	/**
	 * Does any of datagrid columns has a filter?
	 * @param  string
	 * @return bool
	 */
	public function hasFilters($type = NULL)
	{
		return count($type == NULL ? $this->getFilters() : $this->getFilters($type)) > 0;
	}


	/**
	 * Does datagrid has any action?
	 * @param  string
	 * @return bool
	 */
	public function hasActions($type = NULL)
	{
		return count($type == NULL ? $this->getActions() : $this->getActions($type)) > 0;
	}


	/**
	 * Does datagrid has any operation?
	 * @return bool
	 */
	public function hasOperations()
	{
		return count($this->operations) > 0;
	}



	/********************* component's state *********************/



	/**
	 * Loads params
	 * @param  array
	 * @return void
	 */
	public function loadState(array $params)
	{
		if ($this->rememberState) {
			$session = $this->getStateSession();

			if (!isset($session->currentState)) {
				$session->currentState = $session->initState;
			}

			if (isset($session->currentState)) {
				$cs = $session->currentState;
				$is = $session->initState;

				foreach ($cs as $key => $value) {
					if ($cs[$key] != $is[$key]) {

						// additional input validation
						switch ($key) {
							case 'page': $value = ($value > 0 ? $value : 1); break;
							case 'order': break;
							case 'filters': break;
							case 'itemsPerPage': break;
						}
						$params[$key] = $value;
					}
				}
			}
		}
		parent::loadState($params);
	}


	/**
	 * Save params
	 * @param  array
	 * @return void
	 */
	public function saveState(array & $params)
	{
		parent::saveState($params);

		if ($this->rememberState) {
			$session = $this->getStateSession();

			// backup component's state
			if (!isset($session->initState)) {
				$session->initState = array(
					'page' => $this->page,
					'order' => $this->order,
					'filters' => $this->filters,
					'itemsPerPage' => $this->itemsPerPage,
				);
			}

			// save component's state into session
			$session->currentState = $params;
			$session->setExpiration($this->timeout);
		}
	}


	/**
	 * Restores component's state.
	 * @param  string
	 * @return void
	 */
	public function restoreState()
	{
		$session = $this->getStateSession();

		// restore components's init state
		if (isset($session->initState)) {
			$is = $session->initState;
			$this->page = $is['page'];
			$this->order = $is['order'];
			$this->filters = $is['filters'];
			$this->itemsPerPage = $is['itemsPerPage'];
		}

		$session->remove();
	}


	/**
	 * Returns array of classes persistent parameters.
	 * @param  string  class name
	 * @return array
	 */
	public static function getPersistentParams()
	{
		return array('page', 'order', 'filters', 'itemsPerPage');
	}



	/********************* signal handlers ********************/



	/**
	 * Changes page number.
	 * @param  int
	 * @return void
	 */
	public function handlePage($goto)
	{
		$this->page = ($goto > 0 ? $goto : 1);
		$this->invalidateControl();
		if (!$this->presenter->isAjax()) $this->redirect('this');
	}


	/**
	 * Changes column sorting order.
	 * @param  string
	 * @param  string
	 * @return void
	 */
	public function handleOrder($by, $dir)
	{
		// default ordering
		if (empty($this->order) && !empty($this->defaultOrder)) {
			parse_str($this->defaultOrder, $list);
			if (isset($list[$by])) $this->order = $this->defaultOrder;
			unset($list);
		}

		parse_str($this->order, $list);

		if ($dir == NULL) {
			if (!isset($list[$by])) {
				if (!$this->multiOrder) $list = array();
				$list[$by] = 'a';

			} elseif ($list[$by] === 'd') {
				if ($this->multiOrder) unset($list[$by]);
				else $list[$by] = 'a';

			} else {
				$list[$by] = 'd';
			}

		} else {
			if (!$this->multiOrder) $list = array();
			$list[$by] = $dir;
		}

		$this->order = http_build_query($list, '', '&');
		$this->invalidateControl();
		if (!$this->presenter->isAjax()) $this->redirect('this');
	}


	/**
	 * Prepare filtering.
	 * @param  string
	 * @return void
	 */
	public function handleFilter($by)
	{
		$filters = array();
		foreach ($by as $key => $value) {
			if ($value !== '') $filters[$key] = $value;
		}
		$this->filters = http_build_query($filters, '', '&');

		$this->invalidateControl();
		if (!$this->presenter->isAjax()) $this->redirect('this');
	}


	/**
	 * Change number of displayed items.
	 * @param  string
	 * @return void
	 */
	public function handleItems($value)
	{
		if ($value < 0) {
			throw new InvalidArgumentException("Parametr must be non-negative number, '$value' given.");
		}
		$this->itemsPerPage = $value;

		$this->invalidateControl();
		if (!$this->presenter->isAjax()) $this->redirect('this');
	}


	/**
	 * Change component's state.
	 * @param  string
	 * @return void
	 */
	public function handleReset()
	{
		$this->restoreState();

		$this->invalidateControl();
		if (!$this->presenter->isAjax()) $this->redirect('this');
	}



	/********************* submit handlers *********************/



	/**
	 * Data grid form submit handler.
	 * @param  AppForm
	 * @return void
	 */
	public function formSubmitHandler(AppForm $form)
	{
		$this->receivedSignal = 'submit';

		// was form submitted?
		if ($form->isSubmitted()) {
			$values = $form->getValues();

			if ($form['filterSubmit']->isSubmittedBy()) {
				$this->handleFilter($values['filters']);

			} elseif ($form['pageSubmit']->isSubmittedBy()) {
				$this->handlePage($values['page']);

			} elseif ($form['itemsSubmit']->isSubmittedBy()) {
				$this->handleItems($values['items']);

			} elseif ($form['resetSubmit']->isSubmittedBy()) {
				$this->handleReset();

			} elseif ($form['operationSubmit']->isSubmittedBy()) {
				if (!is_array($this->onOperationSubmit)) {
					throw new InvalidStateException('No user defined handler for operations; assign valid callback to operations handler into DataGrid::$operationsHandler variable.');
				}

			} else {
				throw new InvalidStateException("Unknown submit button.");
			}

		}
		if (!$this->presenter->isAjax()) $this->presenter->redirect('this');
	}



	/********************* applycators (call before rendering only) *********************/


	/**
	 * Aplycators caller - filters data grid items.
	 * @return void
	 */
	protected function filterItems()
	{
		// must be in this order
		$this->applyDefaultFiltering();
		$this->applyDefaultSorting();
		$this->applyItems();
		$this->applyFiltering();
		$this->applySorting();
		$this->applyPaging();
	}


	/**
	 * Applies default sorting on data grid.
	 * @return void
	 */
	protected function applyDefaultSorting()
	{
		if (empty($this->order) && !empty($this->defaultOrder)) {
			$this->order = $this->defaultOrder;
		}
	}


	/**
	 * Applies default filtering on data grid.
	 * @return void
	 */
	protected function applyDefaultFiltering()
	{
		if (empty($this->filters) && !empty($this->defaultFilters)) {
			$this->filters = $this->defaultFilters;
		}
	}


	/**
	 * Applies paging on data grid.
	 * @return void
	 */
	protected function applyPaging()
	{
		$this->paginator->page = $this->page;
		$this->paginator->itemCount = count($this->dataSource);

		if ($this->wasRendered && $this->paginator->itemCount < 1 && !empty($this->filters)) {
			// NOTE: don't use flash messages (because you can't - header already sent)
			$this->getTemplate()->flashes[] = (object) array(
				'message' => $this->translate("Used filters did not match any items."),
				'type' => 'info',
			);
		}
		$this->dataSource->applyLimit($this->paginator->length, $this->paginator->offset);
	}


	/**
	 * Applies sorting on data grid.
	 * @return void
	 */
	protected function applySorting()
	{
		$i = 1;
		parse_str($this->order, $list);
		foreach ($list as $field => $dir) {
			$this->dataSource->orderBy($field, $dir === 'a' ? dibi::ASC : dibi::DESC);
			$list[$field] = array($dir, $i++);
		}
		return $list;
	}


	/**
	 * Applies filtering on data grid.
	 * @return void
	 */
	protected function applyFiltering()
	{
		if (!$this->hasFilters()) return;

		parse_str($this->filters, $list);
		foreach ($list as $column => $value) {
			if ($value !== '') {
				$this[$column]->applyFilter($value);
			}
		}
	}


	/**
	 * Applies filtering on data grid.
	 * @return void
	 */
	protected function applyItems()
	{
		$value = (int) $this->itemsPerPage;

		if ($value == 0) {
			$this->itemsPerPage = $this->paginator->itemsPerPage = count($this->dataSource);
		} else {
			$this->itemsPerPage = $this->paginator->itemsPerPage = $value;
		}
	}



	/********************* renderers *********************/



	/**
	 * Sets data grid renderer.
	 * @param  IDataGridRenderer
	 * @return void
	 */
	public function setRenderer(IDataGridRenderer $renderer)
	{
		$this->renderer = $renderer;
	}


	/**
	 * Returns data grid renderer.
	 * @return IDataGridRenderer|NULL
	 */
	public function getRenderer()
	{
		if ($this->renderer === NULL) {
			$this->renderer = new DataGridRenderer;
		}
		return $this->renderer;
	}


	/**
	 * Renders data grid.
	 * @return void
	 */
	public function render()
	{
		if (!$this->wasRendered) {
			$this->wasRendered = TRUE;

			if (!$this->hasColumns() || (count($this->getColumns('ActionColumn')) == count($this->getColumns()))) {
				$this->generateColumns();
			}

			if ($this->disableOrder) {
				foreach ($this->getColumns() as $column) {
					$column->orderable = FALSE;
				}
			}

			if ($this->hasActions() || $this->hasOperations()) {
				if ($this->keyName == NULL) {
					throw new InvalidStateException("Name of key for operations or actions was not set for DataGrid '" . $this->getName() . "'.");
				}
			}

			if (!count($this->dataSource)) {
				$this->flashMessage($this->translate("Empty datasource given."), 'info');
			}

			// NOTE: important!
			$this->filterItems();

			// TODO: na r20 funguje i: $this->getForm()->isSubmitted()
			if ($this->isSignalReceiver('submit')) {
				$this->regenerateFormControls();
			}
		}

		$args = func_get_args();
		array_unshift($args, $this);
		$s = call_user_func_array(array($this->getRenderer(), 'render'), $args);

		echo mb_convert_encoding($s, 'HTML-ENTITIES', 'UTF-8');
	}


	/**
	 * Template factory.
	 * @return ITemplate
	 */
	protected function createTemplate()
	{
		$template = parent::createTemplate();
		if ($this->getTranslator() !== NULL) {
			$template->setTranslator($this->getTranslator());
		}
		//$template->registerFilter('Nette\Templates\CurlyBracketsFilter::invoke');
		return $template;
	}



	/********************* components handling *********************/



	/**
	 * Component factory.
	 * @see Nette/ComponentContainer#createComponent()
	 */
	protected function createComponentForm($name)
	{
		// NOTE: signal-submit on form disregard component's state
		//		because form is created directly by Presenter in signal handling phase
		//		and this principle is used to detect submit signal
		if (!$this->wasRendered) {
			$this->receivedSignal = 'submit';
		}

		$form = new AppForm($this, $name);
		$form->setTranslator($this->getTranslator());
		FormControl::$idMask = 'frm-datagrid-' . $this->getUniqueId() . '-%s-%s';
		$form->onSubmit[] = array($this, 'formSubmitHandler');

		$form->addSubmit('resetSubmit', 'Reset state');
		$form->addSubmit('filterSubmit', 'Apply filters');

		$form->addSelect('operations', 'Selected:', $this->operations);
		$form->addSubmit('operationSubmit', 'Send')->onClick = $this->onOperationSubmit;

		// page input
		$form->addText('page', 'Page', 1);
		$form['page']->setDefaultValue($this->page);
		$form->addSubmit('pageSubmit', 'Change page');

		// items per page selector
		$form->addSelect('items', 'Items per page', array_combine($this->displayedItems, $this->displayedItems));
		$form['items']->setDefaultValue($this->itemsPerPage);
		$form->addSubmit('itemsSubmit', 'Change');

		// generate filters FormControls
		if ($this->hasFilters()) {
			$defaults = array();
			$sub = $form->addContainer('filters');
			foreach ($this->getFilters() as $filter) {
				$sub->addComponent($filter->getFormControl(), $filter->getName());
				// NOTE: must be setted after is FormControl conntected to the form
				$defaults[$filter->getName()] = $filter->value;
			}
			$sub->setDefaults($defaults);
		}

		// checker
		if ($this->hasOperations()) {
			$sub = $form->addContainer('checker');

			if ($this->isSignalReceiver('submit')) {
				// NOTE: important!
				$ds = clone $this->dataSource;
				$this->filterItems();
			}

			foreach ($this->getRows() as $row) {
				$sub->addCheckbox($row[$this->keyName], $row[$this->keyName]);
			}

			if (isset($ds)) $this->dataSource = $ds;
		}

		$renderer = $form->getRenderer();
		$renderer->wrappers['controls']['container'] = NULL;
		$renderer->wrappers['label']['container'] = NULL;
		$renderer->wrappers['control']['container'] = NULL;
		$form->setRenderer($renderer);
		return;
	}


	/**
	 * Returns data grid's form component.
	 * @param  bool   throw exception if form doesn't exist?
	 * @return AppForm
	 */
	public function getForm($need = TRUE)
	{
		return $this->getComponent('form', $need);
	}


	/**
	 * Generates filter controls and checker's checkbox controls
	 * @param  AppForm
	 * @return void
	 */
	protected function regenerateFormControls()
	{
		$form = $this->getForm();

		// regenerate checker's checkbox controls
		if ($this->hasOperations()) {
			$values = $form->getValues();

			$form->removeComponent($form['checker']);
			$sub = $form->addContainer('checker');
			foreach ($this->getRows() as $row) {
				$sub->addCheckbox($row[$this->keyName], $row[$this->keyName]);
			}

			if (!empty($values['checker'])) {
				$form->setDefaults(array('checker' => $values['checker']));
			}
		}

		// for selectbox filter controls update values if was filtered over column
		if ($this->hasFilters()) {
			parse_str($this->filters, $list);

			foreach ($this->getFilters() as $filter) {
				if ($filter instanceof SelectboxFilter) {
					$filter->generateItems();
				}

				if ($this->filters === $this->defaultFilters && ($filter->value !== NULL || $filter->value !== '')) {
					if (!in_array($filter->getName(), array_keys($list))) $filter->value = NULL;
				}
			}
		}

		// page input & items selectbox
		$form['page']->setValue($this->paginator->page); // intentionally page from paginator
		$form['items']->setValue($this->paginator->itemsPerPage);
	}


	/**
	 * Allows operations and adds checker (column filled by checkboxes).
	 * @param  array  list of operations (selectbox items)
	 * @param  mixed  valid callback handler which provides rutines from $operations
	 * @param  string column name used to identifies each item/record in data grid (name of primary key of table/query from data source is recomended)
	 * @return void
	 */
	public function allowOperations(array $operations, $callback = NULL, $key = NULL)
	{
		$this->operations = $operations;

		if ($key != NULL && $this->keyName == NULL) {
			$this->keyName = $key;
		}
		if ($callback != NULL && $this->onOperationSubmit == NULL) {
			 $this->setOnOperationSubmit($callback);
		}
	}


	/**
	 * Generates columns from datasource.
	 * @return void
	 */
	protected function generateColumns()
	{
		if ($this->hasColumns('ActionColumn')) {
			$columns = $this->getColumns('ActionColumn');
			foreach ($columns as $column) {
				unset($this[$column->getName()]);
			}
		}

		$ds = clone $this->dataSource;
		$row = $ds->select('*')->fetch();
		$keys = array_keys((array)$row);
		foreach ($keys as $key) $this->addColumn($key);

		if (isset($columns)) {
			foreach ($columns as $column) {
				$this[$column->getName()] = $column;
				$this->setCurrentActionColumn($column);
			}
		}
	}



	/********************* component factories *********************/



	/**
	 * Adds column of textual values.
	 * @param  string  control name
	 * @param  string  column label
	 * @param  int     maximum number of dislayed characters
	 * @return TextColumn
	 */
	public function addColumn($name, $caption = NULL, $maxLength = NULL)
	{
		return $this[$name] = new TextColumn($caption, $maxLength);
	}


	/**
	 * Adds column of numeric values.
	 * @param  string  control name
	 * @param  string  column label
	 * @param  int     number of digits after the decimal point
	 * @return NumericColumn
	 */
	public function addNumericColumn($name, $caption = NULL, $precision = 2)
	{
		return $this[$name] = new NumericColumn($caption, $precision);
	}


	/**
	 * Adds column of date-represented values.
	 * @param  string  control name
	 * @param  string  column label
	 * @param  string  date format
	 * @return DateColumn
	 */
	public function addDateColumn($name, $caption = NULL, $format = '%x')
	{
		return $this[$name] = new DateColumn($caption, $format);
	}


	/**
	 * Adds column of boolean values (represented by checkboxes).
	 * @param  string  control name
	 * @param  string  column label
	 * @return CheckboxColumn
	 */
	public function addCheckboxColumn($name, $caption = NULL)
	{
		return $this[$name] = new CheckboxColumn($caption);
	}


	/**
	 * Adds column of graphical images.
	 * @param  string  control name
	 * @param  string  column label
	 * @return ImageColumn
	 */
	public function addImageColumn($name, $caption = NULL)
	{
		return $this[$name] = new ImageColumn($caption);
	}


	/**
	 * Adds column which provides moving entries up or down.
	 * @param  string  control name
	 * @param  string  column label
	 * @param  string  destination or signal to handler which do the move rutine
	 * @param  array   textual labels for generated links
	 * @param  bool    use ajax? (add class DataGridColumn::$ajaxClass into generated link)
	 * @return PositionColumn
	 */
	public function addPositionColumn($name, $caption = NULL, $destination = NULL, array $moves = NULL, $useAjax = TRUE)
	{
		return $this[$name] = new PositionColumn($caption, $destination, $moves);
	}


	/**
	 * Adds column which represents logic container for data grid actions.
	 * @param  string  control name
	 * @param  string  column label
	 * @param  bool
	 * @return ActionColumn
	 */
	public function addActionColumn($name, $caption = NULL, $setAsCurrent = TRUE)
	{
		$column = new ActionColumn($caption);

		if ($setAsCurrent) {
			$this->setCurrentActionColumn($column);
		}
		return $this[$name] = $column;
	}


	/**
	 * @param  ActionColumn
	 * @return void
	 */
	public function setCurrentActionColumn(ActionColumn $column)
	{
		$this->currentActionColumn = $column;
	}


	/**
	 * Action factory.
	 * @param  string  textual title
	 * @param  string  textual link destination
	 * @param  Html    element which is added to a generated link
	 * @param  bool    use ajax? (add class self::$ajaxClass into generated link)
	 * @param  mixed   generate link with argument? (if yes you can specify name of parameter
	 * 				   otherwise variable DataGrid::$keyName will be used and must be defined)
	 * @return DataGridAction
	 */
	public function addAction($title, $signal, $icon = NULL, $useAjax = FALSE, $key = DataGridAction::WITH_KEY)
	{
		if (!$this->hasColumns('ActionColumn')) {
			throw new InvalidStateException('No ActionColumn defined. Use DataGrid::addActionColumn before you add actions.');
		}

		return $this->currentActionColumn->addAction($title, $signal, $icon, $useAjax, $key);
	}



	/********************* translator ********************/



	/**
	 * Sets translate adapter.
	 * @param  ITranslator
	 * @return void
	 */
	public function setTranslator(ITranslator $translator = NULL)
	{
		$this->translator = $translator;
	}


	/**
	 * Returns translate adapter.
	 * @return ITranslator|NULL
	 */
	final public function getTranslator()
	{
		return $this->translator;
	}


	/**
	 * Returns translated string.
	 * @param  string
	 * @return string
	 */
	public function translate($s)
	{
		$args = func_get_args();
		return $this->translator === NULL ? $s : call_user_func_array(array($this->getTranslator(), 'translate'), $args);
	}



	/********************* interface \ISignalReceiver *********************/



	/**
	 * Checks if component is signal receiver.
	 * @param  string  signal name
	 * @return bool
	 */
	public function isSignalReceiver($signal = TRUE)
	{
		if ($signal == 'submit') {
			return $this->receivedSignal === 'submit';
		} else {
			return $this->getPresenter()->isSignalReceiver($this, $signal);
		}

		// TODO: zatim musi byt reseno takto protoze nize uvedene reseni neni funkcni
		// TODO: dokud nebude vyreseno toto tema http://forum.nettephp.com/cs/1813-metoda-issignalreceiver-v-komponentach
		// TODO: pak odstranit i promennou receivedSignal
		//return $this->getPresenter()->isSignalReceiver($signal == 'submit' ? $this->getForm() : $this, $signal);
	}



	/********************* backend *********************/



	/**
	 * @return SessionNamespace
	 */
	protected function getStateSession()
	{
		return $this->getSession()->getNamespace('Nette.Extras.DataGrid/' . $this->getName() . '/states');
	}


	/**
	 * @return Session
	 */
	protected function getSession()
	{
		return Environment::getSession();
	}


	/**
	 * Renders table grid and return as string.
	 * @return string
	 */
	public function __toString()
	{
		$s = call_user_func_array(array($this->getRenderer(), 'render'), array($this));
		return mb_convert_encoding($s, 'HTML-ENTITIES', 'UTF-8');
	}
}
Back to Top