【CakePHP2.2】タスクアプリケーションの作成
Controller
<?php class TasksController extends AppController{ public $scaffold; public function index(){ $options = array( 'conditions' => array( 'Task.status' => 0 ) ); $tasks_data = $this->Task->find('all',$options); //debug($tasks_data); $this->set('tasks_data',$tasks_data); } public function done(){ //URL末尾から取得更新 $id = $this->request->pass[0]; $this->Task->id = $id; $this->Task->saveField('status',1);//DB書き込み $msg = sprintf('タスク %s を完了',$id); $this->flash($msg,'/tasks/index'); } public function create(){ if($this->request->is('post')){ $data = array( 'name' => $this->request->data['name'], 'body' => $this->request->data['body'], ); //data登録 $id = $this->Task->save($data);// save if($id === false){ $this->render('create'); return; } $msg = sprintf('タスク %s を登録',$this->Task->id); $this->Session->setFlash($msg); $this->redirect('/tasks/index'); } } public function edit(){ $id = $this->request->pass[0]; //条件 $options = array( 'conditions' => array( 'Task.id' => $id, 'Task.status' => 0 ) ); $task = $this->Task->find('first',$options); //データ見つからない場合は一覧へ if($task == false){ $this->Session->setFlash('タスクが見つかりません'); $this->redirect('/Tasks/index'); } //フォームが送信されたら更新にトライ if($this->request->is('post')){ $data = array( 'id' => $id, 'name' => $this->request->data['Task']['name'], 'body' => $this->request->data['Task']['body'] ); if($this->Task->save($data)){ $this->Session->setFlash('更新しました'); $this->redirect('/Tasks/index'); } }else{ //postされてない場合は初期データをフォームにセット $this->request->data = $task; } } }
Model
<?php class Task extends AppModel{ public $validate = array( 'name' => array( 'rule' => array('maxLength',60), 'required' => true, 'allowEmpty' => false, 'message' => 'タスク名を入力してください' ), 'body' => array( 'rule' => array('maxLength',255), 'required' => true, 'allowEmpty' => false, 'message' => '詳細を入力してください' ) ); public $hasMany = array('Note'); }
View
index.ctp
a href='/Tasks/create'>new task</a> <BR> <?php echo count($tasks_data);?>件のタスクが未完了 <table> <?php foreach($tasks_data as $row): ?> <tr> <td><a href="/Tasks/view/<?php echo $row['Task']['id']; ?>">このタスクをえらぶ </a></td> <td><a href="/Tasks/edit/<?php echo $row['Task']['id']; ?>">編集</a></td> <td><?php echo $row['Task']['name']; ?></td> <td><a href="/tasks/done/<?php echo $row['Task']['id']; ?>">完了する</a></td> <td> <?php foreach($row['Note'] as $note): ?> <?php echo h($note['body']); ?> <?php endforeach; ?> </td> </tr> <?php endforeach; ?> </table>
create.ctp
<form action="/Tasks/create" method="POST"> name<input type="text" name="name" size="40"> <?php echo $this->Form->error('Task.name'); ?> body<input type="text" name="body" size="255"> <?php echo $this->Form->error('Task.body'); ?> <input type="submit" value="タスク作成"> </form>
edit.ctp
<?php echo $this->Form->create('Task',array('type' => 'post')); echo $this->Form->input('Task.name',array('label' => 'タイトル')); echo $this->Form->input('Task.body',array('label' => '詳細')); echo $this->Form->end('保存');