Ubiquity 2.5.2
php rapid development framework
Loading...
Searching...
No Matches
CRUDController.php
Go to the documentation of this file.
1<?php
2
4
13use Ajax\semantic\html\collections\HtmlMessage;
14use Ajax\common\html\HtmlContentOnly;
16use Ajax\semantic\widgets\datatable\DataTable;
17
27 protected $model;
28 protected $activePage=1;
29 protected $style;
30
31 public function __construct() {
32 parent::__construct ();
33 DAO::$transformerOp = 'toView';
34 $this->style = '';
35 $this->_insertJquerySemantic ();
36 }
37
43 protected function refreshAsJson($instances){
44 $objects = \array_map ( function ($o) {
45 return $o->_rest;
46 }, $instances );
47 return \json_encode(\array_values ( $objects ));
48 }
49
50 public function _setStyle($elm) {
51 if ($this->style === 'inverted') {
52 $elm->setInverted ( true );
53 if ($elm instanceof DataTable) {
54 $elm->setActiveRowSelector ( 'black' );
55 }
56 }
57 }
58
65 public function index() {
66 $objects = $this->getInstances ( $totalCount ,$this->activePage);
67 $modal = ($this->_getModelViewer ()->isModal ( $objects, $this->model )) ? "modal" : "no";
68 $dt = $this->_getModelViewer ()->getModelDataTable ( $objects, $this->model, $totalCount ,$this->activePage);
69 $this->jquery->getOnClick ( '#btAddNew', $this->_getBaseRoute () . '/newModel/' . $modal, '#frm-add-update', [ 'hasLoader' => 'internal' ] );
70 $this->_getEvents ()->onDisplayElements ( $dt, $objects, false );
71 $this->crudLoadView ( $this->_getFiles ()->getViewIndex (), [ 'classname' => $this->model,'messages' => $this->jquery->semantic ()->matchHtmlComponents ( function ($compo) {
72 return $compo instanceof HtmlMessage;
73 } ) ] );
74 }
75
83 #[\Ubiquity\attributes\items\router\Post]
84 public function updateMember($member, $callback = false) {
85 $instance = $_SESSION ['instance'] ?? null;
86 if (isset ( $instance )) {
87 $this->_getEvents ()->onBeforeUpdateRequest ( $_POST, false );
88 $updated = CRUDHelper::update ( $instance, $_POST, true, true, function ($inst) {
89 $this->_getEvents ()->onBeforeUpdate ( $inst, false );
90 } );
91 if ($updated) {
92 if ($callback === false) {
93 $dt = $this->_getModelViewer ()->getModelDataTable ( [ $instance ], $this->model, 1 );
94 $dt->setGroupByFields(null);
95 $dt->compile ();
96 echo new HtmlContentOnly ( $dt->getFieldValue ( $member ) );
97 } else {
98 if (\method_exists ( $this, $callback )) {
99 $this->$callback ( $member, $instance );
100 } else {
101 throw new \Exception ( "The method `" . $callback . "` does not exists in " . get_class () );
102 }
103 }
104 } else {
105 UResponse::setResponseCode ( 404 );
106 }
107 } else {
108 throw new \Exception ( '$_SESSION["instance"] is null' );
109 }
110 }
111
115 public function refresh_() {
117 if (isset ( $_POST ['s'] )) {
118 $instances = $this->search ( $model, $_POST ['s'] );
119 } else {
120 $page = URequest::post ( 'p', 1 );
121 $instances = $this->getInstances ( $totalCount, $page );
122 }
123 if (! isset ( $totalCount )) {
124 $totalCount = DAO::count ( $model, $this->_getAdminData ()->_getInstancesFilter ( $model ) );
125 }
126 $recordsPerPage = $this->_getModelViewer ()->recordsPerPage ( $model, $totalCount );
127 $grpByFields = $this->_getModelViewer ()->getGroupByFields ();
128 if (isset ( $recordsPerPage )) {
129 if (! is_array ( $grpByFields )) {
130 UResponse::asJSON ();
131 echo $this->refreshAsJson($instances);
132 } else {
133 $this->_renderDataTableForRefresh ( $instances, $model, $totalCount );
134 }
135 } else {
136 $this->jquery->execAtLast ( '$("#search-query-content").html("' . $_POST ['s'] . '");$("#search-query").show();$("#table-details").html("");' );
137 $this->_renderDataTableForRefresh ( $instances, $model, $totalCount );
138 }
139 }
140
147 public function edit($modal = "no", $ids = "") {
148 if (URequest::isAjax ()) {
149 $instance = $this->getModelInstance ( $ids, false );
150 $instance->_new = false;
151 $this->_edit ( $instance, $modal );
152 } else {
153 $this->jquery->execAtLast ( "$('._edit[data-ajax={$ids}]').trigger('click');" );
154 $this->index ();
155 }
156 }
157
163 public function newModel($modal = "no") {
164 if (URequest::isAjax ()) {
166 $instance = new $model ();
167 $this->_getEvents()->onNewInstance($instance);
168 $instance->_new = true;
169 $this->_edit ( $instance, $modal );
170 } else {
171 $this->jquery->execAtLast ( "$('.ui.button._new').trigger('click');" );
172 $this->index ();
173 }
174 }
175
182 #[\Ubiquity\attributes\items\router\Post]
183 public function editMember($member) {
184 $ids = URequest::post ( "id" );
185 $td = URequest::post ( "td" );
186 $part = URequest::post ( "part" );
187 $instance = $this->getModelInstance ( $ids, false, $member );
188 $_SESSION ["instance"] = $instance;
189 $instance->_new = false;
190 $form = $this->_getModelViewer ()->getMemberForm ( "frm-member-" . $member, $instance, $member, $td, $part, 'updateMember' );
191 $form->setLibraryId ( "_compo_" );
192 $this->jquery->renderView ( "@framework/main/component.html" );
193 }
194
201 public function display($modal = "no", $ids = "") {
202 if (URequest::isAjax ()) {
203 $instance = $this->getModelInstance ( $ids );
204 $key = OrmUtils::getFirstKeyValue ( $instance );
205 $this->jquery->execOn ( "click", "._close", '$("#table-details").html("");$("#dataTable").show();' );
206 $this->jquery->getOnClick ( "._edit", $this->_getBaseRoute () . "/edit/" . $modal . "/" . $key, "#frm-add-update" );
207 $this->jquery->getOnClick ( "._delete", $this->_getBaseRoute () . "/delete/" . $key, "#table-messages" );
208
209 $this->_getModelViewer ()->getModelDataElement ( $instance, $this->model, $modal );
210 $this->jquery->renderView ( $this->_getFiles ()->getViewDisplay (), [ "classname" => $this->model,"instance" => $instance,"pk" => $key ] );
211 } else {
212 $this->jquery->execAtLast ( "$('._display[data-ajax={$ids}]').trigger('click');" );
213 $this->index ();
214 }
215 }
216
223 #[\Ubiquity\attributes\items\router\Route(methods: ['get','post'])]
224 public function delete($ids) {
225 if (URequest::isAjax ()) {
226 $instance = $this->getModelInstance ( $ids );
227 $instanceString = $this->getInstanceToString ( $instance );
228 if (\count ( $_POST ) > 0) {
229 try {
230 if (DAO::remove ( $instance )) {
231 $message = new CRUDMessage ( "Deletion of `<b>" . $instanceString . "</b>`", "Deletion", "info", "info circle", 4000 );
232 $message = $this->_getEvents ()->onSuccessDeleteMessage ( $message, $instance );
233 $this->jquery->exec ( "$('._element[data-ajax={$ids}]').remove();", true );
234 } else {
235 $message = new CRUDMessage ( "Can not delete `" . $instanceString . "`", "Deletion", "warning", "warning circle" );
236 $message = $this->_getEvents ()->onErrorDeleteMessage ( $message, $instance );
237 }
238 } catch ( \Exception $e ) {
239 $message = new CRUDMessage ( "Exception : can not delete `" . $instanceString . "`", "Exception", "warning", "warning" );
240 $message = $this->_getEvents ()->onErrorDeleteMessage ( $message, $instance );
241 }
242 $message = $this->showSimpleMessage_ ( $message );
243 } else {
244 $message = new CRUDMessage ( "Do you confirm the deletion of `<b>" . $instanceString . "</b>`?", "Remove confirmation", "error", "question circle" );
245 $message = $this->_getEvents ()->onConfDeleteMessage ( $message, $instance );
246 $message = $this->showConfMessage_ ( $message, $this->_getBaseRoute () . "/delete/{$ids}", "#table-messages", $ids );
247 }
248 echo $message;
249 echo $this->jquery->compile ( $this->view );
250 } else {
251 $this->jquery->execAtLast ( "$('._delete[data-ajax={$ids}]').trigger('click');" );
252 $this->index ();
253 }
254 }
255
256 public function refreshTable($id = null) {
257 $compo = $this->_showModel ( $id );
258 $this->jquery->execAtLast ( '$("#table-details").html("");' );
259 $compo->setLibraryId ( "_compo_" );
260 $this->jquery->renderView ( "@framework/main/component.html" );
261 }
262
270 #[\Ubiquity\attributes\items\router\Post]
271 public function updateModel() {
272 $message = new CRUDMessage ( "Modifications were successfully saved", "Updating" );
273 $instance = $_SESSION ["instance"] ?? null;
274 if (isset ( $instance )) {
275 $isNew = $instance->_new;
276 try {
277 $this->_getEvents ()->onBeforeUpdateRequest ( $_POST, $isNew );
278 $updated = CRUDHelper::update ( $instance, $_POST, true, true, function ($inst, $isNew) {
279 $this->_getEvents ()->onBeforeUpdate ( $inst, $isNew );
280 } );
281 if ($updated) {
282 $message->setType ( "success" )->setIcon ( "check circle outline" );
283 $message = $this->_getEvents ()->onSuccessUpdateMessage ( $message, $instance );
284 $this->refreshInstance ( $instance, $isNew );
285 } else {
286 $message->setMessage ( "An error has occurred. Can not save changes." )->setType ( "error" )->setIcon ( "warning circle" );
287 $message = $this->_getEvents ()->onErrorUpdateMessage ( $message, $instance );
288 }
289 } catch ( \Exception $e ) {
290 $instanceString = $this->getInstanceToString ( $instance );
291 $message = new CRUDMessage ( "Exception : can not update `" . $instanceString . "`", "Exception", "warning", "warning" );
292 $message = $this->_getEvents ()->onErrorUpdateMessage ( $message, $instance );
293 }
294 echo $this->showSimpleMessage_ ( $message, "updateMsg" );
295 echo $this->jquery->compile ( $this->view );
296 return $instance;
297 } else {
298 throw new \Exception ( '$_SESSION["instance"] is null' );
299 }
300 }
301
307 public function showDetail($ids) {
308 if (URequest::isAjax ()) {
309 $instance = $this->getModelInstance ( $ids );
310 $viewer = $this->_getModelViewer ();
311 $hasElements = false;
313 $fkInstances = CRUDHelper::getFKIntances ( $instance, $model );
314 $semantic = $this->jquery->semantic ();
315 $grid = $semantic->htmlGrid ( 'detail' );
316 if (($nb = \count ( $fkInstances )) > 0) {
317 $wide = intval ( 16 / $nb );
318 if ($wide < 4) {
319 $wide = 4;
320 }
321 foreach ( $fkInstances as $member => $fkInstanceArray ) {
322 $element = $viewer->getFkMemberElementDetails ( $member, $fkInstanceArray ['objectFK'], $fkInstanceArray ['fkClass'], $fkInstanceArray ['fkTable'] );
323 if (isset ( $element )) {
324 $grid->addCol ( $wide )->setContent ( $element );
325 $hasElements = true;
326 }
327 }
328 if ($hasElements) {
329 echo $grid;
330 $url = $this->_getFiles ()->getDetailClickURL ( $this->model );
331 if (UString::isNotNull ( $url )) {
332 $this->detailClick ( $url );
333 }
334 }
335 echo $this->jquery->compile ( $this->view );
336 }
337 } else {
338 $this->jquery->execAtLast ( "$('tr[data-ajax={$ids}]').trigger('click');" );
339 $this->index ();
340 }
341 }
342
343 public function detailClick($url,$responseElement='#divTable',$attributes=[ "attr" => "data-ajax"]) {
344 $this->jquery->postOnClick ( ".showTable", $this->_getBaseRoute () . "/" . $url, "{}", $responseElement, $attributes );
345 }
346}
Default controller used in a new project.
Ubiquity\controllers\crud$CRUDController This class is part of Ubiquity.
__construct()
Constructor initialize $view variable.
index()
Default page : list all objects Uses modelViewer.isModal, modelViewer.getModelDataTable Uses CRUDFile...
refreshAsJson($instances)
Return a JSON representation of $instances for the JsonDataTable component.
detailClick($url, $responseElement='#divTable', $attributes=["attr"=> "data-ajax"])
edit($modal="no", $ids="")
Edits an instance.
refresh_()
Refreshes the area corresponding to the DataTable.
showDetail($ids)
Shows associated members with foreign keys.
updateModel()
Updates an instance from the data posted in a form.
newModel($modal="no")
Adds a new instance and edits it.
display($modal="no", $ids="")
Displays an instance.
showConfMessage_(CRUDMessage $message, $url, $responseElement, $data, $attributes=null)
showSimpleMessage_(CRUDMessage $message, $staticName=null)
static getFKIntances($instance, $model, $included=false)
static update($instance, $values, $setValues=true, $updateMany=true, $eventCallback=null)
Gateway class between database and object model.
Definition DAO.php:33
Object/relational mapping utilities.
Definition OrmUtils.php:17
String utilities.
Definition UString.php:15
Http Request utilities, wrapper for accessing to $_GET, $_POST and php://input.
Definition URequest.php:18
Http Response utilities.
Definition UResponse.php:17