codeigniter standard crud model


/ Published in: PHP
Save to your folder(s)

none


Copy this code and paste it in your HTML
  1. <?php
  2. class Crud extends Model {
  3. /*create the array to pass to the views*/
  4. var $data = array();
  5. var $form = array();
  6. var $controller;
  7. function Crud()
  8. {
  9. // Call the Model constructor
  10. parent::Model();
  11. $this->load->helper('form');
  12. $this->load->helper('url');
  13. $this->load->library('errors');
  14. $this->load->library('validation');
  15. $this->load->database();
  16. $this->load->model('display');
  17.  
  18. $this->form =
  19. ('sites' => array
  20. (
  21. 'id' => array('ID number of this site',
  22. 'readonly', 'numeric'),
  23. 'name' => array('Name of site', 'textarea',
  24. 'alpha_numeric'),
  25. 'url' => array('Qualified URL,
  26. eg http://www.example.com', 'input', ''),
  27. 'un' => array('username to log in to site',
  28. 'input', 'numeric|xss_clean'),
  29. 'pw' => array('password for site', 'input',
  30. 'xss_clean'),
  31.  
  32. 'client1' => array('Main client',
  33. 'dropdown', '', 'people' ),
  34. 'client2' => array('Second client', 'dropdown',
  35. '', 'people'),
  36. 'admin1' => array('First admin', 'dropdown',
  37. '', 'people'),
  38. 'admin2' => array( 'Second Admin', 'dropdown',
  39. '', 'people'),
  40. 'domainid' => array('Domain name', 'dropdown',
  41. 'numeric', 'domains'),
  42. 'hostid' => array( 'Host', 'dropdown',
  43. 'numeric', 'hosts'),
  44. 'submit' => array( 'Enter details', 'submit', 'mumeric')
  45. ),
  46. 'domains' => array
  47. (
  48. 'id' => array('ID number of this domain',
  49. 'hidden', 'numeric'),
  50. //etc etc etc!!
  51.  
  52.  
  53. /*this function lists all the entries in a database table on one page. Note that every db table must have an 'id' field and a 'name' field to display!
  54. This page is a jumping-off point for the other functions - ie to create, read, update or delete an entry.
  55. When you've done any of these, you are returned to this page. It has a 'message' parameter, so you can return with a message - either success or failure.*/
  56. function showall($controller='', $message = '', $test ='no')
  57. {
  58. $result = '';
  59. $mysess = $this->session->userdata('session_id');
  60. $mystat = $this->session->userdata('status');
  61. if(!$this->db->table_exists($controller))
  62. {
  63. $place = __FILE__.__LINE__;
  64. $outcome = "exception:$place:looking for table $controller: it doesn't exist'";
  65. /*test block: what if there is no controller by that name?*/
  66. if($test =='yes')
  67. {
  68. return $outcome;
  69. }
  70. else{
  71. $this->failure($outcome, 'sites');
  72. }
  73. }
  74.  
  75. /*end test block*/
  76. $this->db->select('id, name');
  77. $query = $this->db->get($controller);
  78. if ($query->num_rows() > 0)
  79. {
  80. $result .= "<table class='table'>";
  81.  
  82. $result .= "<tr><td colspan='3'><h3>$controller</h3></
  83. td></tr>";
  84. $result .= "<tr><td colspan='3' class='message'>
  85. $message</td></tr>";
  86. $result .= "<tr><td colspan='3'>";
  87. $result .= anchor("$controller/insert/0", 'New entry');
  88. $result .= "</td></tr>";
  89. $result .= "<tr><td colspan='3'>";
  90. $result .= anchor("$controller/read",
  91. 'Show all entries in the table');
  92. $result .= "</td></tr>";
  93. foreach ($query->result() as $row)
  94. {
  95. $result .= "<tr><td>";
  96. $result .= $row->id;
  97. $result .= " ";
  98. $result .= $row->name;
  99. $result .= "</td><td>";
  100. $result .= anchor("$controller/insert/
  101. $row->id",'Update this entry');
  102. $result .= "</td><td>";
  103. $result .= anchor("$controller/delete/
  104. $row->id",'Delete');
  105. $result .= "</td></tr>";
  106. }
  107. $result .= "</table>";
  108. $data['text'] = $result;
  109. $this->display->mainpage($data, $this->status);
  110. }
  111. else
  112. {$place = __FILE__.__LINE__;
  113. $outcome = "exception: $place:
  114. no results from table $controller";
  115. /*test block: were there results from this table/ controller?*/
  116. if($test == 'yes')
  117. {$place = __FILE__.__LINE__;
  118. return $outcome;
  119. }
  120. /*end test block*/
  121. else{
  122. $message = "No data in the $controller table";
  123. /*note: this specific exception must return to another controller which you know does contain data…… otherwise, it causes an infinite loop! */
  124. $this->failure($message, 'sites');
  125. }
  126. }
  127. }
  128.  
  129. /*queries the table to show all data, and formats it as an HTML table.*/
  130. function read($controller)
  131. {
  132. $this->load->library('table');
  133. $tmpl = array (
  134. 'table_open' => '<table border="1" cellpadding="4" cellspacing="0" width="100%">',
  135. 'row_alt_start' => '<tr bgcolor="grey">',
  136. );
  137. $this->table->set_template($tmpl);
  138. $this->load->database();
  139. $this->load->library('table');
  140. $query = $this->db->get($controller);
  141.  
  142. $result = $this->table->generate($query);
  143. $data['text'] = $result;
  144. $this->display->mainpage($data);
  145. }
  146.  
  147. /*DELETE FUNCTION: given table name and id number, deletes an entry*/
  148. function delete($controller, $idno, $state='no', $test='no')
  149. {
  150. /*first check that the 'yes' flag is set. If not, go through the trydelete function to give them a chance to change their minds*/
  151. if(!isset($state) || $state != 'yes')
  152. {
  153. /*test block: are 'yes' flags recognised?*/
  154. if($test == 'yes')
  155. {
  156. $place = __FILE__.__LINE__;
  157. $outcome = "exception at $place: sent state value $state to trydelete function ";
  158. return $outcome;
  159. }
  160. else
  161. /*end test block*/
  162. {$this->trydelete($controller, $idno, 'no');}
  163. }
  164. else{
  165. /*'yes' flag is set, so now make sure there is an id number*/
  166. if(isset($idno) && $idno > 0 && is_int($idno))
  167. /*test block: with this id no, am I going to do a delete?*/
  168. {
  169. if($test == 'yes')
  170. {
  171. $place = __FILE__.__LINE__;
  172. $outcome = "OK at $place:
  173. doing delete on id of $idno ";
  174.  
  175. return $outcome;
  176. }
  177. else{
  178. /*end test block*/
  179. /*if there is an id number, do the delete*/
  180. $this->db->where('id', $idno);
  181. $this->db->delete($controller);
  182. $changes = $this->db->affected_rows();
  183. }
  184. if($changes != 1)
  185. {
  186. /*test block: did I actually do a delete? */
  187. $place = __FILE__.__LINE__;
  188. $outcome = "exception at $place: cdnt do delete op on $controller with id no of $idno";
  189. if($test == 'yes')
  190. {return $outcome;}
  191. else
  192. /*end test block*/
  193. /*if there was no update, report it*/
  194. {$this->failure($outcome);}
  195. }
  196. else{
  197. /*test block: I did do a delete*/
  198. if($test == 'yes')
  199. {return 'OK';}
  200. else{
  201. /*end test block: report the delete*/
  202. $this->showall($controller,
  203. "Entry no. $idno deleted.");}
  204. }
  205. }
  206. else
  207. /*test block: report id number wasn't acceptable'*/
  208. {
  209. $place = __FILE__.__LINE__;
  210. $outcome = "exception at: $place : id no of $idno set for delete op in $controller, expecting integer";
  211. if($test == 'yes')
  212. {return $outcome;}
  213. else
  214. /*endtest block: if I failed, report me*/
  215. {$this->failure($outcome);}
  216. }
  217. }
  218. }
  219.  
  220. /*TRYDELETE FUNCION: interrupts deletes with an 'are you sure? screen'*/
  221. function trydelete($controller, $idno, $submit = 'no')
  222. {
  223. if($state == 'yes')
  224. {$this->delete($controller, $idno, 'yes');}
  225. else{
  226. $result .= "<table><tr><td>Are you sure you want to delete this entry?</td></tr>";
  227. $result .= form_open("$controller/delete");
  228. $result .= form_hidden('id', $idno);
  229. $result .= "<tr><td>";
  230. $result .= form_submit('submit', 'yes');
  231. $result .= "</td></tr>";
  232. $result .= form_close();
  233. $result .= "</table>";
  234. $result .= anchor("$controller/showall",
  235. "No, don't delete");
  236. $data['text'] = $result;
  237. $this->display->mainpage($data);
  238. }
  239. }
  240.  
  241. /*the most complex function. This creates an HTML form, based on the description of the fields in the form array. This is sent to our display model, which sets up a view and shows it to the user.
  242. The view then sends a POST array back to the controller. The form can't call this model directly, so it has to call the controller, which refers it back to the model.
  243. Note the function parameters:
  244. 1. The controller parameter is whichever controller/ table has called the model - eg the 'sites' controller, or the 'domains' controller. The controller has the same name as the table it manipulates.
  245. 2. The optional id parameter is the id of an individual entry in that table.
  246. 3. The optional 'test' parameter is so you can set the form up to make usable responses to self-test functions.
  247. */
  248. function insert($controller='', $id=0, $test='no')
  249. {
  250. $myform = '';
  251. $myid = 0;
  252. $currentvalue = array();
  253. /*test if the table exists*/
  254. if(!$this->db->table_exists($controller))
  255. {
  256. $place = __FILE__.__LINE__;
  257. $outcome = "exception: $place:looking for table $controller: it doesn't exist'";
  258. if($test =='yes')
  259. {
  260. return $outcome;
  261. }
  262. else{
  263. $this->failure($outcome, $controller);
  264. }
  265. }
  266. else
  267. {
  268. if($test =='yes')
  269. {
  270. return 'OK';
  271. }
  272. }
  273. /*end test block*/
  274. /*next check if there is an id number. If there is, we need to get the values to populate the table fields*/
  275. if(isset($id) && $id > 0)
  276. {$myid = $id;
  277. $this->db->where('id', $id);
  278. $query = $this->db->get($controller);
  279. if ($query->num_rows() > 0)
  280. {
  281. $row = $query->row();
  282. //--------------work out the values we want!
  283. foreach($row as $key =>$value)
  284. /*
  285. first of all work out what value you want to show as the existing value in each line of the form. In priority order these are:
  286. 1. the last value the user entered, from the post array
  287. 2. the value from the database
  288. 3. nothing, if neither of these is set.
  289. if we got here, the id does exist and is returning values, so get the existing values into a value array. Or, if there is something in the validation array, use that instead*/
  290. {
  291. $_POST[$key] = $this->validation->$key;
  292.  
  293. if(isset($_POST[$key]))
  294. {$currentvalue[$key] = $_POST[$key];}
  295. else
  296. {$currentvalue[$key] = $value;}
  297. }
  298. /*test block: there was an id number, so has the program gone for an update? if this is not a test, of course, just do the update*/
  299. if($test == 'yes')
  300. {
  301. $place = __FILE__.__LINE__;
  302. $outcome = "exception: $place: id of $id returned results from $controller table so have gone for update";
  303. return $outcome;
  304. }
  305. /*end test block*/
  306. $myform .= "<tr><td colspan='2'>Update existing entry number $id</td></tr>";
  307. }
  308. /*now catch situation where this query isn't returning results. We could only have got here with an integer set as our ID number, so
  309. this probably means we are trying to delete an entry that doesn't
  310. exist.*/
  311. else{
  312. $place = __FILE__.__LINE__;
  313. $outcome = "exception: $place: despite id of $id cant get any results from $controller table";
  314. if($test == 'yes')
  315. /*test block: there was and ID but there were no results*/
  316. {
  317. return $outcome;
  318. }
  319. /*end test block*/
  320. else
  321. {$this->failure($outcome, $controller);}
  322. }
  323. }
  324. /*there was no ID number, so this is a new entry*/
  325. else{
  326. /*If the user has filled in values, and has returned here because some of them didn't validate, we still need to repopulate the form with what he entered, so he only has to alter the one that didn't validate. Get these from the post array*/
  327. if(isset($_POST))
  328. {
  329. foreach($_POST as $key => $value)
  330.  
  331. {
  332. if(isset($_POST[$key]))
  333. {$currentvalue[$key] = $_POST[$key];}
  334. }
  335. }
  336. $myform .= "<tr><td colspan='2'>New entry</td></tr>";
  337. /*test block: there was no ID, so this is a new entry*/
  338. if($test == 'yes')
  339. {
  340. $place = __FILE__.__LINE__;
  341. $outcome = "exception: $place: id of $id treated as no id, so going for new entry";
  342. return $outcome;
  343. }
  344. /*end test block*/
  345. }
  346. /*the table exists, whether this is an update or new entry, so start to build the form*/
  347. $myform .= "<table class='table'>";
  348. $myform .= form_open("$controller/interim");
  349. $myform .= '<p>This entry could not be made because...</P>';
  350. $myform .= $this->validation->error_string;
  351. /*the rest of this function is common to inserts or update.
  352. Look up in the form array which form field type you want to display, and then build up the html for each different type, as well as inserting the values you want it to echo.*/
  353. foreach($this->form[$controller] as $key => $value)
  354. {
  355. /*This switch statement develops several types of HTML form field based on information in the form array.
  356. It doesn't yet cover checkboxes or radio or password fields. It adds a 'readonly' type, which is a field that only displays a value and doesn't let the user modify it*/
  357. $fieldtype = $value[1];
  358. $val_string = $this->validation->$key;
  359. switch($value[1])
  360. {
  361. /*a simple input line*/
  362. case 'input':
  363. $data = array(
  364. 'name' => $key,
  365.  
  366. 'id' => $key,
  367. 'value' => $currentvalue[$key],
  368. 'maxlength' => '100',
  369. 'size' => '50',
  370. 'style' => 'width:50%',
  371. );
  372. $myform .= "<tr><td>$value[0]</td><td>";
  373. $myform .= form_input($data);
  374. $myform .= "</td></tr>";
  375. if($test == 'second')
  376. {
  377. return 'input';
  378. }
  379. break;
  380. case 'textarea':
  381. /*a text area field.*/
  382. $data = array(
  383. 'name' => $key,
  384. 'id' => $key,
  385. 'value' => $currentvalue[$key],
  386. 'rows' => '6',
  387. 'cols' => '70',
  388. 'style' => 'width:50%',
  389. );
  390. $myform .= "<tr><td valign=
  391. 'top'>$value[0]</td><td>";
  392. $myform .= form_textarea($data);
  393. $myform .= "</td></tr>";
  394. break;
  395. case 'dropdown':
  396. /*a drop-down box. Values are dynamically generated from whichever table was specified in the forms array. This table must have an id field (which is now entered in the form) and a name field (which is displayed in the drop-down box).*/
  397. $dropbox = array();
  398. if(isset($value[3]))
  399. {
  400. $temptable = $value[3];
  401. $this->db->select('id, name');
  402. $query = $this->db->get($temptable);
  403. if ($query->num_rows() > 0)
  404. {
  405. foreach ($query->result() as $row)
  406. {
  407. $dropbox[$row->id] = $row->name;
  408. }
  409. }
  410. }
  411.  
  412. $myform .= "<tr><td valign=
  413. 'top'>$value[0]</td><td>";
  414. $myform .= form_dropdown($key, $dropbox, $currentvalue[$key]);
  415. $myform .= "</td></tr>";
  416. break;
  417. case 'submit':
  418. /*a submit field*/
  419. $myform .= "<tr><td>$value[0]</td><td>";
  420. $time = time();
  421. $data = array(
  422. 'name' => 'submit',
  423. 'id' => 'submit',
  424. );
  425. $myform .= form_submit($data);
  426. $myform .= "</td></tr>";
  427. break;
  428. case 'hidden':
  429. /*generates a hidden field*/
  430. $myform .= form_hidden($key, $currentvalue[$key]);
  431. break;
  432. case 'readonly':
  433. /*generates a field the user can see, but not alter.*/
  434. $myform .= "<tr><td>$value[0]</td><td>$currentvalue[$key]";
  435. $myform .= form_hidden($key, $currentvalue[$key]);
  436. $myform .= "</td></tr>";
  437. break;
  438. case 'timestamp':
  439. /*generates a timestamp the first time it's set*/
  440. // $myform .= "<tr><td>$value[0]</td><td>now()";
  441. $timenow = time();
  442. if($currentvalue[$key]==''||$currentvalue[$key]==0)
  443. {$time = $timenow;}
  444. else{$time = $currentvalue[$key];}
  445. $myform .= form_hidden($key, $time);
  446. $myform .= "</td></tr>";
  447. break;
  448. case 'updatestamp':
  449. /*generates a timestamp each time it's altered or viewed*/
  450. // $myform .= "<tr><td>$value[0]</td><td>now()";
  451.  
  452. $timenow = time();
  453. $myform .= form_hidden($key, $timenow);
  454. $myform .= "</td></tr>";
  455. break;
  456. default:
  457. $place = __FILE__.__LINE__;
  458. $outcome = "exception: $place:
  459. switch can't handle $fieldtype";
  460. /*test block: what if the switch doesn't recognise the form type?'*/
  461. if($test == 'second')
  462. {
  463. return $outcome;
  464. }
  465. /*test block ends*/
  466. else {
  467. $this->failure($outcome, $controller);
  468. }
  469. }
  470. /*end the foreach loop which generates the form*/
  471. }
  472. $myform .= form_hidden('submit',$time);
  473. $myform .= form_close();
  474. $myform .= "</table>";
  475. /*Finally we've built our form and populated it! Now, stuff the form in an array variable and send it to the model which builds up the rest of the view.*/
  476. $data['text'] = $myform;
  477. $this->display->mainpage($data);
  478. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.