Ubiquity  2.0.3
php rapid development framework
ModelsTrait.php
Go to the documentation of this file.
1 <?php
2 
4 
17 
24 
25  protected $activePage;
26 
27  protected $formModal="no";
28 
29  abstract public function _getAdminData();
30 
31  abstract public function _getAdminViewer();
32 
33  abstract public function _getModelViewer();
34 
35  abstract public function _getAdminFiles();
36 
37  abstract protected function showSimpleMessage($content, $type, $title=null,$icon="info", $timeout=NULL, $staticName=null):HtmlMessage;
38 
39  public function showTable($table,$id=null) {
40  $model=$this->getModelsNS() . "\\" . ucfirst($table);
41  $adminRoute=$this->_getAdminFiles()->getAdminBaseRoute();
42  $this->_showModel($model,$id);
43  $this->_getAdminViewer()->getModelsStructureDataTable(OrmUtils::getModelMetadata($model));
44  $bt=$this->jquery->semantic()->htmlButton("btYuml", "Class diagram");
45  $bt->postOnClick($adminRoute. "/_showDiagram/", "{model:'" . \str_replace("\\", "|", $model) . "'}", "#modal", [ "attr" => "" ]);
46  $this->jquery->exec('$("#models-tab .item").tab();', true);
47  $this->jquery->getOnClick ( "#btAddNew", $adminRoute . "/newModel/" . $this->formModal, "#frm-add-update",["hasLoader"=>"internal"] );
48  $this->jquery->compile($this->view);
49  $this->loadView($this->_getAdminFiles()->getViewShowTable(), [ "classname" => $model ]);
50  }
51 
52  public function refreshTable($id=null) {
53  $model=$_SESSION["model"];
54  $compo= $this->_showModel($model,$id);
55  $this->jquery->execAtLast('$("#table-details").html("");');
56  $this->jquery->renderView("@framework/Admin/main/component.html",["compo"=>$compo]);
57  }
58 
59  public function showTableClick($tableAndId) {
60  $array=\explode(".", $tableAndId);
61  if (\is_array($array)) {
62  $table=$array[0];
63  $id=$array[1];
64  $this->jquery->exec("$('#menuDbs .active').removeClass('active');$('.ui.label.left.pointing.teal').removeClass('left pointing teal active');$(\"[data-ajax='" . $table . "']\").addClass('active');$(\"[data-ajax='" . $table . "']\").find('.ui.label').addClass('left pointing teal');", true);
65  $this->showTable($table,$id);
66  $this->jquery->execAtLast("$(\"tr[data-ajax='" . $id . "']\").click();");
67  echo $this->jquery->compile();
68  }
69  }
70 
71  protected function _showModel($model,$id=null) {
72  $_SESSION["model"]=$model;
73  $datas=$this->getInstances($model,1,$id);
74  $this->formModal=($this->_getModelViewer()->isModal($datas,$model))? "modal" : "no";
75  return $this->_getModelViewer()->getModelDataTable($datas, $model,$this->activePage);
76  }
77 
78  protected function getInstances($model,$page=1,$id=null){
79  $this->activePage=$page;
80  $recordsPerPage=$this->_getModelViewer()->recordsPerPage($model,DAO::count($model));
81  if(is_numeric($recordsPerPage)){
82  if(isset($id)){
83  $rownum=DAO::getRownum($model, $id);
84  $this->activePage=Pagination::getPageOfRow($rownum,$recordsPerPage);
85  }
86  return DAO::paginate($model,$this->activePage,$recordsPerPage);
87  }
88  return DAO::getAll($model);
89  }
90 
91  protected function search($model,$search){
92  $fields=$this->_getAdminData()->getSearchFieldNames($model);
93  return CRUDHelper::search($model, $search, $fields);
94  }
95 
96  public function refresh_(){
97  $model=$_POST["_model"];
98  if(isset($_POST["s"])){
99  $instances=$this->search($model, $_POST["s"]);
100  }else{
101  $instances=$this->getInstances($model,URequest::post("p",1));
102  }
103  $recordsPerPage=$this->_getModelViewer()->recordsPerPage($model,DAO::count($model));
104  if(isset($recordsPerPage)){
106  $responseFormatter=new ResponseFormatter();
107  print_r($responseFormatter->getJSONDatas($instances));
108  }else{
109  $this->formModal=($this->_getModelViewer()->isModal($instances,$model))? "modal" : "no";
110  $compo= $this->_getModelViewer()->getModelDataTable($instances, $model)->refresh(["tbody"]);
111  $this->jquery->execAtLast('$("#search-query-content").html("'.$_POST["s"].'");$("#search-query").show();$("#table-details").html("");');
112  $this->jquery->renderView("@framework/Admin/main/component.html",["compo"=>$compo]);
113  }
114  }
115 
116  protected function _edit($instance, $modal="no") {
117  $_SESSION["instance"]=$instance;
118  $modal=($modal == "modal");
119  $form=$this->_getModelViewer()->getForm("frmEdit", $instance);
120  $this->jquery->click("#action-modal-frmEdit-0", "$('#frmEdit').form('submit');", false);
121  if (!$modal) {
122  $this->jquery->click("#bt-cancel", "$('#form-container').transition('drop');");
123  $this->jquery->compile($this->view);
124  $this->loadView($this->_getAdminFiles()->getViewEditTable(), [ "modal" => $modal ]);
125  } else {
126  $this->jquery->exec("$('#modal-frmEdit').modal('show');", true);
127  $form=$form->asModal(\get_class($instance));
128  $form->setActions([ "Okay","Cancel" ]);
129  $btOkay=$form->getAction(0);
130  $btOkay->addClass("green")->setValue("Validate modifications");
131  $form->onHidden("$('#modal-frmEdit').remove();");
132  echo $form->compile($this->jquery, $this->view);
133  echo $this->jquery->compile($this->view);
134  }
135  }
136 
137  public function edit($modal="no", $ids="") {
138  $instance=$this->getModelInstance($ids);
139  $instance->_new=false;
140  $this->_edit($instance, $modal);
141  }
142 
143  public function newModel($modal="no") {
144  $model=$_SESSION["model"];
145  $instance=new $model();
146  $instance->_new=true;
147  $this->_edit($instance, $modal);
148  }
149 
150  public function update() {
151  $message=new CRUDMessage("Modifications were successfully saved", "Updating");
152  $instance=@$_SESSION["instance"];
153  $isNew=$instance->_new;
154  $updated=CRUDHelper::update($instance, $_POST,$this->_getAdminData()->getUpdateManyToOneInForm(),$this->_getAdminData()->getUpdateManyToManyInForm());
155  if($updated){
156  $pk=OrmUtils::getFirstKeyValue($instance);
157  $message->setType("success")->setIcon("check circle outline");
158  if($isNew){
159  $this->jquery->get($this->_getAdminFiles()->getAdminBaseRoute() . "/refreshTable/".$pk, "#lv", [ "jqueryDone" => "replaceWith" ]);
160  }else{
161  $this->jquery->setJsonToElement(OrmUtils::objectAsJSON($instance));
162  }
163  } else {
164  $message->setMessage("An error has occurred. Can not save changes.")->setType("error")->setIcon("warning circle");
165  }
166  echo $this->_showSimpleMessage($message,"updateMsg");
167  echo $this->jquery->compile($this->view);
168  }
169 
170  private function getModelInstance($ids) {
171  $model=$_SESSION['model'];
172  $ids=\explode("_", $ids);
173  $instance=DAO::getOne($model, $ids);
174  if(isset($instance)){
175  return $instance;
176  }
177  echo $this->showSimpleMessage("This object does not exist!", "warning","Get object","warning circle");
178  echo $this->jquery->compile($this->view);
179  exit(1);
180  }
181 
182  public function delete($ids) {
183  $instance=$this->getModelInstance($ids);
184  if (method_exists($instance, "__toString"))
185  $instanceString=$instance . "";
186  else
187  $instanceString=get_class($instance);
188  if (sizeof($_POST) > 0) {
189  if (DAO::remove($instance)) {
190  $message=$this->showSimpleMessage("Deletion of `<b>" . $instanceString . "</b>`", "info","Deletion", "info", 4000);
191  $this->jquery->exec("$('tr[data-ajax={$ids}]').remove();", true);
192  } else {
193  $message=$this->showSimpleMessage("Can not delete `" . $instanceString . "`", "warning","Error", "warning");
194  }
195  } else {
196  $message=$this->showConfMessage("Do you confirm the deletion of `<b>" . $instanceString . "</b>`?", "error","Remove confirmation", $this->_getAdminFiles()->getAdminBaseRoute() . "/delete/{$ids}", "#table-messages", $ids);
197  }
198  echo $message;
199  echo $this->jquery->compile($this->view);
200  }
201 
202  private function getFKMethods($model) {
203  $reflection=new \ReflectionClass($model);
204  $publicMethods=$reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
205  $result=[ ];
206  foreach ( $publicMethods as $method ) {
207  $methodName=$method->getName();
208  if (JString::startswith($methodName, "get")) {
209  $attributeName=lcfirst(JString::replaceAtFirst($methodName, "get", ""));
210  if (!property_exists($model, $attributeName))
211  $result[]=$methodName;
212  }
213  }
214  return $result;
215  }
216 
217  public function showDetail($ids) {
218  $instance=$this->getModelInstance($ids);
219  $viewer=$this->_getModelViewer();
220  $hasElements=false;
221  $model=$_SESSION['model'];
222  $fkInstances=CRUDHelper::getFKIntances($instance, $model);
223  $semantic=$this->jquery->semantic();
224  $grid=$semantic->htmlGrid("detail");
225  if (sizeof($fkInstances) > 0) {
226  $wide=intval(16 / sizeof($fkInstances));
227  if ($wide < 4)
228  $wide=4;
229  foreach ( $fkInstances as $member=>$fkInstanceArray ) {
230  $element=$viewer->getFkMemberElementDetails($member,$fkInstanceArray["objectFK"],$fkInstanceArray["fkClass"],$fkInstanceArray["fkTable"]);
231  if (isset($element)) {
232  $grid->addCol($wide)->setContent($element);
233  $hasElements=true;
234  }
235  }
236  if ($hasElements)
237  echo $grid;
238  $this->jquery->getOnClick(".showTable", $this->_getAdminFiles()->getAdminBaseRoute() . "/showTableClick", "#divTable", [ "attr" => "data-ajax","ajaxTransition" => "random" ]);
239  echo $this->jquery->compile($this->view);
240  }
241 
242  }
243 
244  protected function getModelsNS() {
245  return Startup::getConfig()["mvcNS"]["models"];
246  }
247 
248  private function _getCks($array) {
249  $result=[ ];
250  foreach ( $array as $dataAjax => $caption ) {
251  $result[]=$this->_getCk($caption, $dataAjax);
252  }
253  return $result;
254  }
255 
256  private function _getCk($caption, $dataAjax) {
257  $ck=new HtmlCheckbox("ck-" . $dataAjax, $caption, "1");
258  $ck->setProperty("name", "ck[]");
259  $ck->setProperty("data-ajax", $dataAjax);
260  return $ck;
261  }
262 }
static asJSON()
Sets the response content-type to application/json.
Definition: UResponse.php:72
static getRownum($className, $ids)
Definition: DAO.php:238
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
static paginate($className, $page=1, $rowsPerPage=20, $condition=null)
Definition: DAO.php:231
showSimpleMessage($content, $type, $title=null, $icon="info", $timeout=NULL, $staticName=null)
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
static getFirstKeyValue($instance)
Definition: OrmUtils.php:127
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
static count($className, $condition='')
Returns the number of objects of $className from the database respecting the condition possibly passe...
Definition: DAO.php:347
static getModelMetadata($className)
Definition: OrmUtils.php:19
static getFKIntances($instance, $model)
Definition: CRUDHelper.php:137
getInstances($model, $page=1, $id=null)
Definition: ModelsTrait.php:78
static search($model, $search, $fields, $initialCondition="1=1")
Definition: CRUDHelper.php:28
static remove($instance)
Deletes the object $instance from the database.
static update($instance, $values, $updateManyToOneInForm=true, $updateManyToManyInForm=false)
Definition: CRUDHelper.php:43