Ubiquity  2.0.3
php rapid development framework
CRUDController.php
Go to the documentation of this file.
1 <?php
2 
4 
16 
18  protected $model;
19  protected $modelViewer;
20  protected $events;
21  protected $crudFiles;
22  protected $adminDatas;
23  protected $activePage;
24 
28  public function index() {
29  $objects=$this->getInstances();
30  $modal=($this->_getModelViewer()->isModal($objects,$this->model))?"modal":"no";
31  $this->_getModelViewer()->getModelDataTable($objects, $this->model);
32  $this->jquery->getOnClick ( "#btAddNew", $this->_getBaseRoute() . "/newModel/" . $modal, "#frm-add-update",["hasLoader"=>"internal"] );
33  $this->crudLoadView($this->_getFiles()->getViewIndex(), [ "classname" => $this->model ]);
34  }
35 
36  protected function getInstances($page=1,$id=null){
37  $this->activePage=$page;
39  $condition=$this->_getInstancesFilter($model);
40  $recordsPerPage=$this->_getModelViewer()->recordsPerPage($model,DAO::count($model,$condition));
41  if(is_numeric($recordsPerPage)){
42  if(isset($id)){
43  $rownum=DAO::getRownum($model, $id);
44  $this->activePage=Pagination::getPageOfRow($rownum,$recordsPerPage);
45  }
46  return DAO::paginate($model,$this->activePage,$recordsPerPage);
47  }
48  return DAO::getAll($model,$condition);
49  }
50 
51  public function _getInstancesFilter($model){
52  return "1=1";
53  }
54 
55  protected function search($model,$search){
56  $fields=$this->_getAdminData()->getSearchFieldNames($model);
57  $condition=$this->_getInstancesFilter($model);
58  return CRUDHelper::search($model, $search, $fields,$condition);
59  }
60 
61  public function refresh_(){
63  if(isset($_POST["s"])){
64  $instances=$this->search($model, $_POST["s"]);
65  }else{
66  $instances=$this->getInstances(URequest::post("p",1));
67  }
68  $recordsPerPage=$this->_getModelViewer()->recordsPerPage($model,DAO::count($model,$this->_getInstancesFilter($model)));
69  if(isset($recordsPerPage)){
71  $responseFormatter=new ResponseFormatter();
72  print_r($responseFormatter->getJSONDatas($instances));
73  }else{
74  $this->formModal=($this->_getModelViewer()->isModal($instances,$model))? "modal" : "no";
75  $compo= $this->_getModelViewer()->getModelDataTable($instances, $model)->refresh(["tbody"]);
76  $this->jquery->execAtLast('$("#search-query-content").html("'.$_POST["s"].'");$("#search-query").show();$("#table-details").html("");');
77  $this->jquery->renderView("@framework/main/component.html",["compo"=>$compo]);
78  }
79  }
80 
86  public function edit($modal="no", $ids="") {
87  if(URequest::isAjax()){
88  $instance=$this->getModelInstance($ids);
89  $instance->_new=false;
90  $this->_edit($instance, $modal);
91  }else{
92  $this->jquery->execAtLast("$('._edit[data-ajax={$ids}]').trigger('click');");
93  $this->index();
94  }
95  }
100  public function newModel($modal="no") {
101  if(URequest::isAjax()){
103  $instance=new $model();
104  $instance->_new=true;
105  $this->_edit($instance, $modal);
106  }else{
107  $this->jquery->execAtLast("$('.ui.button._new').trigger('click');");
108  $this->index();
109  }
110  }
111 
117  public function display($modal="no",$ids=""){
118  if(URequest::isAjax()){
119  $instance=$this->getModelInstance($ids);
120  $key=OrmUtils::getFirstKeyValue($instance);
121  $this->jquery->execOn("click","._close",'$("#table-details").html("");$("#dataTable").show();');
122  $this->jquery->getOnClick("._edit", $this->_getBaseRoute()."/edit/".$modal."/".$key,"#frm-add-update");
123  $this->jquery->getOnClick("._delete", $this->_getBaseRoute()."/delete/".$key,"#table-messages");
124 
125  $this->_getModelViewer()->getModelDataElement($instance, $this->model,$modal);
126  $this->jquery->renderView($this->_getFiles()->getViewDisplay(), [ "classname" => $this->model,"instance"=>$instance,"pk"=>$key ]);
127  }else{
128  $this->jquery->execAtLast("$('._display[data-ajax={$ids}]').trigger('click');");
129  $this->index();
130  }
131  }
132 
133  protected function _edit($instance, $modal="no") {
134  $_SESSION["instance"]=$instance;
135  $modal=($modal == "modal");
136  $form=$this->_getModelViewer()->getForm("frmEdit", $instance);
137  $this->jquery->click("#action-modal-frmEdit-0", "$('#frmEdit').form('submit');", false);
138  if (!$modal) {
139  $this->jquery->click("#bt-cancel", "$('#form-container').transition('drop');");
140  $this->jquery->compile($this->view);
141  $this->loadView($this->_getFiles()->getViewForm(), [ "modal" => $modal ]);
142  } else {
143  $this->jquery->exec("$('#modal-frmEdit').modal('show');", true);
144  $form=$form->asModal(\get_class($instance));
145  $form->setActions([ "Okay","Cancel" ]);
146  $btOkay=$form->getAction(0);
147  $btOkay->addClass("green")->setValue("Validate modifications");
148  $form->onHidden("$('#modal-frmEdit').remove();");
149  echo $form->compile($this->jquery, $this->view);
150  echo $this->jquery->compile($this->view);
151  }
152  }
153 
154  protected function _showModel($id=null) {
156  $datas=$this->getInstances(1,$id);
157  $this->formModal=($this->_getModelViewer()->isModal($datas,$model))? "modal" : "no";
158  return $this->_getModelViewer()->getModelDataTable($datas, $model,$this->activePage);
159  }
160 
165  public function delete($ids) {
166  if(URequest::isAjax()){
167  $instance=$this->getModelInstance($ids);
168  if (method_exists($instance, "__toString"))
169  $instanceString=$instance . "";
170  else
171  $instanceString=get_class($instance);
172  if (sizeof($_POST) > 0) {
173  try{
174  if (DAO::remove($instance)) {
175  $message=new CRUDMessage("Deletion of `<b>" . $instanceString . "</b>`","Deletion","info","info circle",4000);
176  $message=$this->_getEvents()->onSuccessDeleteMessage($message);
177  $this->jquery->exec("$('._element[data-ajax={$ids}]').remove();", true);
178  } else {
179  $message=new CRUDMessage("Can not delete `" . $instanceString . "`","Deletion","warning","warning circle");
180  $message=$this->_getEvents()->onErrorDeleteMessage($message);
181  }
182  }catch (\Exception $e){
183  $message=new CRUDMessage("Exception : can not delete `" . $instanceString . "`","Exception", "warning", "warning");
184  $message=$this->_getEvents()->onErrorDeleteMessage($message);
185  }
186  $message=$this->_showSimpleMessage($message);
187  } else {
188  $message=new CRUDMessage("Do you confirm the deletion of `<b>" . $instanceString . "</b>`?", "Remove confirmation","error");
189  $this->_getEvents()->onConfDeleteMessage($message);
190  $message=$this->_showConfMessage($message, $this->_getBaseRoute() . "/delete/{$ids}", "#table-messages", $ids);
191  }
192  echo $message;
193  echo $this->jquery->compile($this->view);
194  }else{
195  $this->jquery->execAtLast("$('._delete[data-ajax={$ids}]').trigger('click');");
196  $this->index();
197  }
198  }
199 
200 
201 
202  public function refreshTable($id=null) {
203  $compo= $this->_showModel($id);
204  $this->jquery->execAtLast('$("#table-details").html("");');
205  $this->jquery->renderView("@framework/main/component.html",["compo"=>$compo]);
206  }
207 
211  public function update() {
212  $message=new CRUDMessage("Modifications were successfully saved", "Updating");
213  $instance=@$_SESSION["instance"];
214  $isNew=$instance->_new;
215  try{
216  $updated=CRUDHelper::update($instance, $_POST,$this->_getAdminData()->getUpdateManyToOneInForm(),$this->_getAdminData()->getUpdateManyToManyInForm());
217  if($updated){
218  $message->setType("success")->setIcon("check circle outline");
219  $message=$this->_getEvents()->onSuccessUpdateMessage($message);
220  $this->refreshInstance($instance,$isNew);
221  } else {
222  $message->setMessage("An error has occurred. Can not save changes.")->setType("error")->setIcon("warning circle");
223  $message=$this->_getEvents()->onErrorUpdateMessage($message);
224  }
225  }catch(\Exception $e){
226  if (method_exists($instance, "__toString"))
227  $instanceString=$instance . "";
228  else
229  $instanceString=get_class($instance);
230  $message=new CRUDMessage("Exception : can not update `" . $instanceString . "`","Exception", "warning", "warning");
231  $message=$this->_getEvents()->onErrorUpdateMessage($message);
232  }
233  echo $this->_showSimpleMessage($message,"updateMsg");
234  echo $this->jquery->compile($this->view);
235  }
236 
237  protected function refreshInstance($instance,$isNew){
238  if($this->_getAdminData()->refreshPartialInstance() && !$isNew){
239  $this->jquery->setJsonToElement(OrmUtils::objectAsJSON($instance));
240  }else{
241  $pk=OrmUtils::getFirstKeyValue($instance);
242  $this->jquery->get($this->_getBaseRoute() . "/refreshTable/".$pk, "#lv", [ "jqueryDone" => "replaceWith" ]);
243  }
244  }
245 
250  public function showDetail($ids) {
251  if(URequest::isAjax()){
252  $instance=$this->getModelInstance($ids);
253  $viewer=$this->_getModelViewer();
254  $hasElements=false;
256  $fkInstances=CRUDHelper::getFKIntances($instance, $model);
257  $semantic=$this->jquery->semantic();
258  $grid=$semantic->htmlGrid("detail");
259  if (sizeof($fkInstances) > 0) {
260  $wide=intval(16 / sizeof($fkInstances));
261  if ($wide < 4)
262  $wide=4;
263  foreach ( $fkInstances as $member=>$fkInstanceArray ) {
264  $element=$viewer->getFkMemberElementDetails($member,$fkInstanceArray["objectFK"],$fkInstanceArray["fkClass"],$fkInstanceArray["fkTable"]);
265  if (isset($element)) {
266  $grid->addCol($wide)->setContent($element);
267  $hasElements=true;
268  }
269  }
270  if ($hasElements)
271  echo $grid;
272  $url=$this->_getEvents()->onDetailClickURL($this->model);
273  if(UString::isNotNull($url)){
274  $this->detailClick($url);
275  }
276  echo $this->jquery->compile($this->view);
277  }
278  }else{
279  $this->jquery->execAtLast("$('tr[data-ajax={$ids}]').trigger('click');");
280  $this->index();
281  }
282 
283  }
284 
285  public function detailClick($url) {
286  $this->jquery->postOnClick(".showTable", $this->_getBaseRoute() . "/".$url,"{}", "#divTable", [ "attr" => "data-ajax","ajaxTransition" => "random" ]);
287  }
288 
289  private function getModelInstance($ids) {
290  $ids=\explode("_", $ids);
291  $instance=DAO::getOne($this->model, $ids);
292  if(isset($instance)){
293  return $instance;
294  }
295  $message=new CRUDMessage("This object does not exist!","Get object","warning","warning circle");
296  $message=$this->_getEvents()->onNotFoundMessage($message);
297  echo $this->_showSimpleMessage($message);
298  echo $this->jquery->compile($this->view);
299  exit(1);
300  }
301 
306  protected function getAdminData ():CRUDDatas{
307  return new CRUDDatas();
308  }
309 
310  public function _getAdminData ():CRUDDatas{
311  return $this->getSingleton($this->modelViewer,"getAdminData");
312  }
313 
318  protected function getModelViewer ():ModelViewer{
319  return new ModelViewer($this);
320  }
321 
322  private function _getModelViewer():ModelViewer{
323  return $this->getSingleton($this->modelViewer,"getModelViewer");
324  }
325 
330  protected function getFiles ():CRUDFiles{
331  return new CRUDFiles();
332  }
333 
334  private function _getFiles():CRUDFiles{
335  return $this->getSingleton($this->crudFiles,"getFiles");
336  }
337 
342  protected function getEvents ():CRUDEvents{
343  return new CRUDEvents();
344  }
345 
346  private function _getEvents():CRUDEvents{
347  return $this->getSingleton($this->events,"getEvents");
348  }
349 
350  private function getSingleton($value, $method) {
351  if (! isset ( $value )) {
352  $value = $this->$method ();
353  }
354  return $value;
355  }
356 
357  private function crudLoadView($viewName,$vars=[]){
358  $this->_getEvents()->beforeLoadView($viewName,$vars);
359  if(!URequest::isAjax()){
360  $files=$this->_getFiles();
361  $mainTemplate=$files->getBaseTemplate();
362  if(isset($mainTemplate)){
363  $vars["_viewname"]=$viewName;
364  $vars["_base"]=$mainTemplate;
365  $this->jquery->renderView($files->getViewBaseTemplate(),$vars);
366  }else{
367  $vars["hasScript"]=true;
368  $this->jquery->renderView($viewName,$vars);
369  }
370  }else{
371  $vars["hasScript"]=true;
372  $this->jquery->renderView($viewName,$vars);
373  }
374  }
375 
376 }
update()
Updates an instance from the data posted in a form.
The base class for displaying datas in CRUD controllers.
Definition: CRUDDatas.php:11
static asJSON()
Sets the response content-type to application/json.
Definition: UResponse.php:72
static getRownum($className, $ids)
Definition: DAO.php:238
getModelViewer()
To override for defining a new ModelViewer.
getAdminData()
To override for defining a new adminData.
static getOne($className, $keyValues, $loadManyToOne=true, $loadOneToMany=false, $useCache=NULL)
Returns an instance of $className from the database, from $keyvalues values of the primary key...
Definition: DAO.php:363
getFiles()
To override for changing view files.
static paginate($className, $page=1, $rowsPerPage=20, $condition=null)
Definition: DAO.php:231
static post($key, $default=NULL)
Returns the value of the $key variable passed by the post method or $default if the $key variable doe...
Definition: URequest.php:146
_showSimpleMessage(CRUDMessage $message, $staticName=null)
static getFirstKeyValue($instance)
Definition: OrmUtils.php:127
loadView($viewName, $pData=NULL, $asString=false)
Loads the view $viewName possibly passing the variables $pdata.
Definition: Controller.php:66
static getAll($className, $condition='', $loadManyToOne=true, $loadOneToMany=false, $useCache=NULL)
Returns an array of $className objects from the database.
Definition: DAO.php:193
static objectAsJSON($instance)
Definition: OrmUtils.php:266
showDetail($ids)
Shows associated members with foreign keys.
_showConfMessage(CRUDMessage $message, $url, $responseElement, $data, $attributes=NULL)
display($modal="no", $ids="")
Displays an instance.
static isAjax()
Returns true if the request is an Ajax request.
Definition: URequest.php:101
static count($className, $condition='')
Returns the number of objects of $className from the database respecting the condition possibly passe...
Definition: DAO.php:347
static getFKIntances($instance, $model)
Definition: CRUDHelper.php:137
getEvents()
To override for changing events.
static search($model, $search, $fields, $initialCondition="1=1")
Definition: CRUDHelper.php:28
edit($modal="no", $ids="")
Edits an instance.
index()
Default page : list all objects.
static remove($instance)
Deletes the object $instance from the database.
static update($instance, $values, $updateManyToOneInForm=true, $updateManyToManyInForm=false)
Definition: CRUDHelper.php:43
newModel($modal="no")
Adds a new instance and edits it.