1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace Grido\Components;
13
14 use Grido\Grid;
15 use Grido\Helpers;
16
17 18 19 20 21 22 23 24 25
26 class Operation extends Component
27 {
28 const ID = 'operations';
29
30
31 public $onSubmit;
32
33
34 protected $primaryKey;
35
36 37 38 39 40
41 public function __construct($grid, array $operations, $onSubmit)
42 {
43 $this->grid = $grid;
44 $grid->addComponent($this, self::ID);
45
46 $grid['form'][$grid::BUTTONS]->addSubmit(self::ID, 'OK')
47 ->onClick[] = $this->handleOperations;
48
49 $grid['form']->addContainer(self::ID)
50 ->addSelect(self::ID, 'Selected', $operations)
51 ->setPrompt('Grido.Selected');
52
53 $that = $this;
54 $grid->onRender[] = function(Grid $grid) use ($that) {
55 $that->addCheckers($grid['form'][Operation::ID]);
56 };
57
58 $this->onSubmit[] = $onSubmit;
59 }
60
61 62 63 64 65 66
67 public function setConfirm($operation, $message)
68 {
69 $message = $this->translate($message);
70 $this->grid->onRender[] = function(Grid $grid) use ($operation, $message) {
71 $grid['form'][Operation::ID][Operation::ID]->controlPrototype->data["grido-confirm-$operation"] = $message;
72 };
73
74 return $this;
75 }
76
77 78 79 80 81
82 public function setPrimaryKey($primaryKey)
83 {
84 $this->primaryKey = $primaryKey;
85 return $this;
86 }
87
88
89
90 91 92
93 public function getPrimaryKey()
94 {
95 if ($this->primaryKey === NULL) {
96 $this->primaryKey = $this->grid->primaryKey;
97 }
98
99 return $this->primaryKey;
100 }
101
102
103
104 105 106 107
108 public function handleOperations(\Nette\Forms\Controls\SubmitButton $button)
109 {
110 $this->grid->onRegistered && $this->grid->onRegistered($this->grid);
111 $form = $button->getForm();
112 $this->addCheckers($form[self::ID]);
113
114 $values = $form[self::ID]->values;
115 if (empty($values[self::ID])) {
116 $httpData = $form->getHttpData();
117 if (!empty($httpData[self::ID][self::ID]) && $operation = $httpData[self::ID][self::ID]) {
118 trigger_error("Operation with name '$operation' does not exist.", E_USER_NOTICE);
119 }
120
121 $this->grid->reload();
122 }
123
124 $ids = array();
125 $operation = $values[self::ID];
126 unset($values[self::ID]);
127
128 foreach ($values as $key => $val) {
129 if ($val) {
130 $ids[] = $key;
131 }
132 }
133
134 $this->onSubmit($operation, $ids);
135 }
136
137 138 139 140
141 public function addCheckers(\Nette\Forms\Container $container)
142 {
143 $items = $this->grid->getData();
144 $primaryKey = $this->getPrimaryKey();
145 $propertyAccessor = $this->grid->getPropertyAccessor();
146
147 foreach ($items as $item) {
148 $primaryValue = $propertyAccessor->getProperty($item, $primaryKey);
149 if (!isset($container[$primaryValue])) {
150 $container->addCheckbox(Helpers::formatColumnName($primaryValue));
151 }
152 }
153 }
154 }
155