Skip to content

Instantly share code, notes, and snippets.

@hugodias
Last active August 29, 2015 13:58
Show Gist options
  • Save hugodias/9974664 to your computer and use it in GitHub Desktop.
Save hugodias/9974664 to your computer and use it in GitHub Desktop.
Cakephp Controller Scaffold
<?php
class CategoriesController extends GerenciadorAppController{
public $components = array('Error');
public function index(){
$this->set('categories', $this->Category->find('all'));
}
public function add(){
$this->set('label', 'Cadastrar categoria');
if($this->request->is('post')){
$this->set('category', $this->request->data);
$this->_saveCategory($this->request->data);
}
$this->render('_form');
}
public function edit($category_id = null){
$this->_setCategory($category_id);
$this->set('label', 'Alterar categoria');
if($this->request->is('post')){
$this->request->data['Category']['id'] = $category_id;
$this->_saveCategory($this->request->data);
}
$this->render('_form');
}
public function delete($category_id = null){
$this->_setCategory($category_id);
if($this->Category->delete()){
$this->Session->setFlash('Categoria removida com sucesso!','flash_success');
} else {
$this->Session->setFlash('Falha ao remover a categoria. Remova todos os produtos que pertencem a ela primeiro.', 'flash_fail');
}
$this->redirect(array('action' => 'index'));
}
private function _saveCategory($data){
if($this->Category->save($data)){
$this->Session->setFlash('Categoria salva com sucesso!','flash_success');
$this->redirect(array('action' => 'index'));
} else {
$this->Error->set($this->Category->invalidFields());
}
}
private function _setCategory($category_id){
$this->Category->id = $category_id;
if(!$this->Category->exists()){
$this->Session->setFlash('Esta categoria não existe.','flash_fail');
$this->redirect(array('action' => 'index'));
}
$this->set('category', $this->Category->read(null));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment