CakePHP3で1Controller、1Templateのページを作る。
題材は画面から身長と体重を入力したらBMIを表示してくれるページ。入力チェックは実施しない。
環境
CakePHP 3.5.10
Controller
src\Controller\BmiController.php
<?php namespace App\Controller; use App\Controller\AppController; class BmiController extends AppController { public function index() { } public function calculate() { //$this->autoRender = false; $height = $this->request->getData('height') / 100; $weight = $this->request->getData('weight'); $this->set('bmi', round($weight / ($height * $height), 1)); $this->render('index'); } }
Template
src\Template\Bmi\index.ctp
<?php $this->layout = false; ?> <!doctype html> <html lang="ja"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <title>bmi calculator</title> </head> <body> <div class="mx-auto" style="width: 400px;"> <h1>bmi calculator</h1> <?php echo $this->Form->create('', ['url' => ['action' => 'calculate']]); echo $this->Form->Control('身長(cm)', ['name' => 'height', 'required']); echo $this->Form->Control('体重(Kg)', ['name' => 'weight', 'required']); echo $this->Form->button('計算する', ['class' => 'btn btn-primary', 'type' => 'submit']); echo $this->Form->button('リセット', ['class' => 'btn', 'type' => 'reset']); echo $this->Form->end(); ?> <?php if (!empty($bmi)): ?> あなたのBMIは<?= $bmi ?>です。 <?php endif; ?> </div> </body> </html>
ControllerとTemplateの作成が終わったらhttp://localhost:8765/bmiにアクセスすると以下のようなページが出力できる。
コメント