cakePHPで商品を表示させるページがあり(goodsテーブルからname,img,priceを取ってくる)、購入ボタンを押すと商品のnameとpriceがorderテーブルに渡される機能を作っています。
GoodsController
<?php namespace App\Controller; use App\Controller\AppController; class GoodsController extends AppController { public function index() { //商品情報取得 $this->set('goods',$this->Goods->find('all')); } function order() { $this->autoRender = false; //購入ボタンおされたときをの情報がorder_tableにいく。goodscontroller内で処理したいが、これだと↓のOrderを読み込まない。 //Ordercontrollerを作る必要があるのか?(viewなど不必要などでいちいちコントローラ必要なのか?などと思ってます) if ($this->request->is('post')) { $good = $this->Orders->newEntity(); $good = $this->Ooders->patchEntity($good, $this->request->data); if ($this->Orders->save($good)) { return $this->redirect(['action' => 'index']); } } } } ?>
Template/Goods/index.ctp
<div> <h1>SHOP</h1> <?php foreach($goods as $good): ?> <?= $this->Form->create(null,[ 'type'=>'post', 'url'=>['controller'=>'Goods','action'=>'order'] ])?> <h2><?= $good->name ?></h2> <div> <?= $good->price ?>円 <?= $this->Form->submit('BUY!') ?> </div> <div><img src="<?= $good->img ?>"></div> <?= $this->Form->hidden('name',['value'=>$good->name]) ?> <?= $this->Form->hidden('price',['value'=>$good->price]) ?> <?= $this->Form->end() ?> <?php endforeach ?> </div>
OrdersController.php(このcontrollerが必要か??)
<?php namespace App\Controller; use App\Controller\AppController; class OrdersController extends AppController { function index() { $this->autoRender = false; //購入ボタンおされたとき if ($this->request->is('post')) { $good = $this->Orders->newEntity(); $good = $this->Orders->patchEntity($good, $this->request->data); if ($this->Orders->save($good)) { return $this->redirect(['action' => 'index']); } } } }
またこのページのviewをmainなどの名前にしてMainControllerの中でactionを分けてこれから追加していく機能をコーディングしていくほうが画面ごとにわかれていて分かりやすそうなのですが、やはりcakeではテーブルごとにひとつずつコントローラを作るのが基本なのでしょうか??
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。