Scaffold.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <?php
  2. /**
  3. * Scaffold.
  4. *
  5. * Automatic forms and actions generation for rapid web application development.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package cake.libs.controller
  18. * @since Cake v 0.10.0.1076
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('Scaffold', 'View');
  22. /**
  23. * Scaffolding is a set of automatic actions for starting web development work faster.
  24. *
  25. * Scaffold inspects your database tables, and making educated guesses, sets up a
  26. * number of pages for each of your Models. These pages have data forms that work,
  27. * and afford the web developer an early look at the data, and the possibility to over-ride
  28. * scaffolded actions with custom-made ones.
  29. *
  30. * @package cake.libs.controller
  31. */
  32. class Scaffold {
  33. /**
  34. * Controller object
  35. *
  36. * @var Controller
  37. */
  38. public $controller = null;
  39. /**
  40. * Name of the controller to scaffold
  41. *
  42. * @var string
  43. */
  44. public $name = null;
  45. /**
  46. * Name of current model this view context is attached to
  47. *
  48. * @var string
  49. */
  50. public $model = null;
  51. /**
  52. * Path to View.
  53. *
  54. * @var string
  55. */
  56. public $viewPath;
  57. /**
  58. * Name of layout to use with this View.
  59. *
  60. * @var string
  61. */
  62. public $layout = 'default';
  63. /**
  64. * Request object
  65. *
  66. * @var CakeRequest
  67. */
  68. public $request;
  69. /**
  70. * valid session.
  71. *
  72. * @var boolean
  73. * @access public
  74. */
  75. protected $_validSession = null;
  76. /**
  77. * List of variables to collect from the associated controller
  78. *
  79. * @var array
  80. * @access private
  81. */
  82. private $__passedVars = array(
  83. 'layout', 'name', 'viewPath', 'request'
  84. );
  85. /**
  86. * Title HTML element for current scaffolded view
  87. *
  88. * @var string
  89. * @access public
  90. */
  91. public $scaffoldTitle = null;
  92. /**
  93. * Construct and set up given controller with given parameters.
  94. *
  95. * @param Controller $controller Controller to scaffold
  96. * @param CakeRequest $request Request parameters.
  97. */
  98. function __construct(Controller $controller, CakeRequest $request) {
  99. $this->controller = $controller;
  100. $count = count($this->__passedVars);
  101. for ($j = 0; $j < $count; $j++) {
  102. $var = $this->__passedVars[$j];
  103. $this->{$var} = $controller->{$var};
  104. }
  105. $this->redirect = array('action' => 'index');
  106. $this->modelClass = $controller->modelClass;
  107. $this->modelKey = $controller->modelKey;
  108. if (!is_object($this->controller->{$this->modelClass})) {
  109. throw new MissingModelException($this->modelClass);
  110. }
  111. $this->ScaffoldModel = $this->controller->{$this->modelClass};
  112. $this->scaffoldTitle = Inflector::humanize(Inflector::underscore($this->viewPath));
  113. $this->scaffoldActions = $controller->scaffold;
  114. $title_for_layout = __d('cake', 'Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle;
  115. $modelClass = $this->controller->modelClass;
  116. $primaryKey = $this->ScaffoldModel->primaryKey;
  117. $displayField = $this->ScaffoldModel->displayField;
  118. $singularVar = Inflector::variable($modelClass);
  119. $pluralVar = Inflector::variable($this->controller->name);
  120. $singularHumanName = Inflector::humanize(Inflector::underscore($modelClass));
  121. $pluralHumanName = Inflector::humanize(Inflector::underscore($this->controller->name));
  122. $scaffoldFields = array_keys($this->ScaffoldModel->schema());
  123. $associations = $this->_associations();
  124. $this->controller->set(compact(
  125. 'title_for_layout', 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
  126. 'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations'
  127. ));
  128. if ($this->controller->viewClass) {
  129. $this->controller->viewClass = 'Scaffold';
  130. }
  131. $this->_validSession = (
  132. isset($this->controller->Session) && $this->controller->Session->valid() != false
  133. );
  134. $this->_scaffold($request);
  135. }
  136. /**
  137. * Outputs the content of a scaffold method passing it through the Controller::afterFilter()
  138. *
  139. * @return void
  140. */
  141. protected function _output() {
  142. $this->controller->afterFilter();
  143. $this->controller->getResponse()->send();
  144. }
  145. /**
  146. * Renders a view action of scaffolded model.
  147. *
  148. * @param CakeRequest $request Request Object for scaffolding
  149. * @return mixed A rendered view of a row from Models database table
  150. */
  151. protected function _scaffoldView(CakeRequest $request) {
  152. if ($this->controller->_beforeScaffold('view')) {
  153. if (isset($request->params['pass'][0])) {
  154. $this->ScaffoldModel->id = $request->params['pass'][0];
  155. }
  156. if (!$this->ScaffoldModel->exists()) {
  157. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey)));
  158. }
  159. $this->ScaffoldModel->recursive = 1;
  160. $this->controller->request->data = $this->ScaffoldModel->read();
  161. $this->controller->set(
  162. Inflector::variable($this->controller->modelClass), $this->request->data
  163. );
  164. $this->controller->render($this->request['action'], $this->layout);
  165. $this->_output();
  166. } elseif ($this->controller->_scaffoldError('view') === false) {
  167. return $this->_scaffoldError();
  168. }
  169. }
  170. /**
  171. * Renders index action of scaffolded model.
  172. *
  173. * @param array $params Parameters for scaffolding
  174. * @return mixed A rendered view listing rows from Models database table
  175. */
  176. protected function _scaffoldIndex($params) {
  177. if ($this->controller->_beforeScaffold('index')) {
  178. $this->ScaffoldModel->recursive = 0;
  179. $this->controller->set(
  180. Inflector::variable($this->controller->name), $this->controller->paginate()
  181. );
  182. $this->controller->render($this->request['action'], $this->layout);
  183. $this->_output();
  184. } elseif ($this->controller->_scaffoldError('index') === false) {
  185. return $this->_scaffoldError();
  186. }
  187. }
  188. /**
  189. * Renders an add or edit action for scaffolded model.
  190. *
  191. * @param string $action Action (add or edit)
  192. * @return mixed A rendered view with a form to edit or add a record in the Models database table
  193. */
  194. protected function _scaffoldForm($action = 'edit') {
  195. $this->controller->viewVars['scaffoldFields'] = array_merge(
  196. $this->controller->viewVars['scaffoldFields'],
  197. array_keys($this->ScaffoldModel->hasAndBelongsToMany)
  198. );
  199. $this->controller->render($action, $this->layout);
  200. $this->_output();
  201. }
  202. /**
  203. * Saves or updates the scaffolded model.
  204. *
  205. * @param CakeRequest $request Request Object for scaffolding
  206. * @param string $action add or edt
  207. * @return mixed Success on save/update, add/edit form if data is empty or error if save or update fails
  208. */
  209. protected function _scaffoldSave(CakeRequest $request, $action = 'edit') {
  210. $formAction = 'edit';
  211. $success = __d('cake', 'updated');
  212. if ($action === 'add') {
  213. $formAction = 'add';
  214. $success = __d('cake', 'saved');
  215. }
  216. if ($this->controller->_beforeScaffold($action)) {
  217. if ($action == 'edit') {
  218. if (isset($request->params['pass'][0])) {
  219. $this->ScaffoldModel->id = $request['pass'][0];
  220. }
  221. if (!$this->ScaffoldModel->exists()) {
  222. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey)));
  223. }
  224. }
  225. if (!empty($request->data)) {
  226. if ($action == 'create') {
  227. $this->ScaffoldModel->create();
  228. }
  229. if ($this->ScaffoldModel->save($request->data)) {
  230. if ($this->controller->_afterScaffoldSave($action)) {
  231. $message = __d('cake',
  232. 'The %1$s has been %2$s',
  233. Inflector::humanize($this->modelKey),
  234. $success
  235. );
  236. return $this->_sendMessage($message);
  237. } else {
  238. return $this->controller->_afterScaffoldSaveError($action);
  239. }
  240. } else {
  241. if ($this->_validSession) {
  242. $this->controller->Session->setFlash(__d('cake', 'Please correct errors below.'));
  243. }
  244. }
  245. }
  246. if (empty($request->data)) {
  247. if ($this->ScaffoldModel->id) {
  248. $this->controller->data = $request->data = $this->ScaffoldModel->read();
  249. } else {
  250. $this->controller->data = $request->data = $this->ScaffoldModel->create();
  251. }
  252. }
  253. foreach ($this->ScaffoldModel->belongsTo as $assocName => $assocData) {
  254. $varName = Inflector::variable(Inflector::pluralize(
  255. preg_replace('/(?:_id)$/', '', $assocData['foreignKey'])
  256. ));
  257. $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
  258. }
  259. foreach ($this->ScaffoldModel->hasAndBelongsToMany as $assocName => $assocData) {
  260. $varName = Inflector::variable(Inflector::pluralize($assocName));
  261. $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
  262. }
  263. return $this->_scaffoldForm($formAction);
  264. } elseif ($this->controller->_scaffoldError($action) === false) {
  265. return $this->_scaffoldError();
  266. }
  267. }
  268. /**
  269. * Performs a delete on given scaffolded Model.
  270. *
  271. * @param array $params Parameters for scaffolding
  272. * @return mixed Success on delete, error if delete fails
  273. */
  274. protected function _scaffoldDelete(CakeRequest $request) {
  275. if ($this->controller->_beforeScaffold('delete')) {
  276. if (!$request->is('post')) {
  277. throw new MethodNotAllowedException();
  278. }
  279. $id = false;
  280. if (isset($request->params['pass'][0])) {
  281. $id = $request->params['pass'][0];
  282. }
  283. $this->ScaffoldModel->id = $id;
  284. if (!$this->ScaffoldModel->exists()) {
  285. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelClass)));
  286. }
  287. if ($this->ScaffoldModel->delete()) {
  288. $message = __d('cake', 'The %1$s with id: %2$d has been deleted.', Inflector::humanize($this->modelClass), $id);
  289. return $this->_sendMessage($message);
  290. } else {
  291. $message = __d('cake',
  292. 'There was an error deleting the %1$s with id: %2$d',
  293. Inflector::humanize($this->modelClass),
  294. $id
  295. );
  296. return $this->_sendMessage($message);
  297. }
  298. } elseif ($this->controller->_scaffoldError('delete') === false) {
  299. return $this->_scaffoldError();
  300. }
  301. }
  302. /**
  303. * Sends a message to the user. Either uses Sessions or flash messages depending
  304. * on the availability of a session
  305. *
  306. * @param string $message Message to display
  307. * @return void
  308. */
  309. protected function _sendMessage($message) {
  310. if ($this->_validSession) {
  311. $this->controller->Session->setFlash($message);
  312. $this->controller->redirect($this->redirect);
  313. } else {
  314. $this->controller->flash($message, $this->redirect);
  315. $this->_output();
  316. }
  317. }
  318. /**
  319. * Show a scaffold error
  320. *
  321. * @return mixed A rendered view showing the error
  322. */
  323. protected function _scaffoldError() {
  324. return $this->controller->render('error', $this->layout);
  325. $this->_output();
  326. }
  327. /**
  328. * When methods are now present in a controller
  329. * scaffoldView is used to call default Scaffold methods if:
  330. * `public $scaffold;` is placed in the controller's class definition.
  331. *
  332. * @param CakeRequest $request Request object for scaffolding
  333. * @return mixed A rendered view of scaffold action, or showing the error
  334. */
  335. protected function _scaffold(CakeRequest $request) {
  336. $db = ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig);
  337. $prefixes = Configure::read('Routing.prefixes');
  338. $scaffoldPrefix = $this->scaffoldActions;
  339. if (isset($db)) {
  340. if (empty($this->scaffoldActions)) {
  341. $this->scaffoldActions = array(
  342. 'index', 'list', 'view', 'add', 'create', 'edit', 'update', 'delete'
  343. );
  344. } elseif (!empty($prefixes) && in_array($scaffoldPrefix, $prefixes)) {
  345. $this->scaffoldActions = array(
  346. $scaffoldPrefix . '_index',
  347. $scaffoldPrefix . '_list',
  348. $scaffoldPrefix . '_view',
  349. $scaffoldPrefix . '_add',
  350. $scaffoldPrefix . '_create',
  351. $scaffoldPrefix . '_edit',
  352. $scaffoldPrefix . '_update',
  353. $scaffoldPrefix . '_delete'
  354. );
  355. }
  356. if (in_array($request->params['action'], $this->scaffoldActions)) {
  357. if (!empty($prefixes)) {
  358. $request->params['action'] = str_replace($scaffoldPrefix . '_', '', $request->params['action']);
  359. }
  360. switch ($request->params['action']) {
  361. case 'index':
  362. case 'list':
  363. $this->_scaffoldIndex($request);
  364. break;
  365. case 'view':
  366. $this->_scaffoldView($request);
  367. break;
  368. case 'add':
  369. case 'create':
  370. $this->_scaffoldSave($request, 'add');
  371. break;
  372. case 'edit':
  373. case 'update':
  374. $this->_scaffoldSave($request, 'edit');
  375. break;
  376. case 'delete':
  377. $this->_scaffoldDelete($request);
  378. break;
  379. }
  380. } else {
  381. throw new MissingActionException(array(
  382. 'controller' => $this->controller->name,
  383. 'action' => $request->action
  384. ));
  385. }
  386. } else {
  387. throw new MissingDatabaseException(array('connection' => $this->ScaffoldModel->useDbConfig));
  388. }
  389. }
  390. /**
  391. * Returns associations for controllers models.
  392. *
  393. * @return array Associations for model
  394. */
  395. protected function _associations() {
  396. $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  397. $associations = array();
  398. foreach ($keys as $key => $type) {
  399. foreach ($this->ScaffoldModel->{$type} as $assocKey => $assocData) {
  400. $associations[$type][$assocKey]['primaryKey'] =
  401. $this->ScaffoldModel->{$assocKey}->primaryKey;
  402. $associations[$type][$assocKey]['displayField'] =
  403. $this->ScaffoldModel->{$assocKey}->displayField;
  404. $associations[$type][$assocKey]['foreignKey'] =
  405. $assocData['foreignKey'];
  406. $associations[$type][$assocKey]['controller'] =
  407. Inflector::pluralize(Inflector::underscore($assocData['className']));
  408. if ($type == 'hasAndBelongsToMany') {
  409. $associations[$type][$assocKey]['with'] = $assocData['with'];
  410. }
  411. }
  412. }
  413. return $associations;
  414. }
  415. }