5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP3実装中の小技いろいろ

Last updated at Posted at 2018-11-02

テンプレート側でwebrootのURLを取得する

Template/Users/index.ctp
$this->Url->build('/')

コントローラへのリンクの書き方

リンク全体を出力する

Template/Users/index.ctp
<?= $this->Html->link( 'ログアウト', ['controller' => 'Users', 'action' => 'logout'], ['class' => 'nav-link']);?>

リンクのURL部分だけ出力する

Template/Users/index.ctp
<a class="nav-link" href="<?= $this->Url->build([ "controller" => "Users", "action" => "index"]);?>">

あるテンプレートでだけ使うJavaScriptを読み込む

全てのページで読み込むJavaScriptであれば、レイアウトのデフォルトのTemplete/Layout/default.ctpに、

Templete/Layout/default.ctp
<?= $this->Html->script('bootstrap.min') ?>

というように書いておけばよいが、あるテンプレートでだけ読み込みたいJavaScriptの場合は、以下のように、そのテンプレートの上の方に書けば良い。
読み込むjsは webroot/js 以下に置いておく。

Template/Users/index.ctp
<?php $this->Html->script('users', ['block' => true]);?>

これはwebroot/js/users.js を読み込む場合である。

読み込まれる場所はレイアウトのテンプレの以下の部分になるので、

Templete/Layout/default.ctp
<?= $this->fetch('script') ?>

こちらの位置を</body>の上に移動しておくとよい。

Paginatorの見出しを日本語の見出しにする

Template/Users/index.ctp
<?= $this->Paginator->sort('username', 'メールアドレス') ?>

日付表示を日本風にする。日付を日本時間にする。

en_US を ja-JP に変える。
UTC を Asia/Tokyo に変える。

config/app.php
    'App' => [
        'namespace' => 'App',
        'encoding' => env('APP_ENCODING', 'UTF-8'),
        'defaultLocale' => env('APP_DEFAULT_LOCALE', 'ja-JP'),
        'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'Asia/Tokyo'),
    ],

テンプレートで登録日の表示を年月日に変更する。

Template/Users/index.ctp
<?= h($user->created->format('Y年m月d日')) ?>

flashメッセージのテンプレートを自作のものに変更する

flashメッセージのテンプレートは Template/Element/Flash以下にあるので、それを元に自作のテンプレートを作成する。

Template/Element/Flash/my_success.ctp
<?php
if (!isset($params['escape']) || $params['escape'] !== false) {
    $message = h($message);
}
?>
<div class="alert alert-success" role="alert" onclick="this.classList.add('hidden')"><?= $message ?></div>

で表示したい場所のテンプレに以下を記述。

Template/Users/add.ctp
<?= $this->Flash->render('flash', ['element' => 'Flash/my_success']);?>

定数や変数の定義をまとめる

まず別ファイルでconst.phpをconfigフォルダー内に作る。

config/const.php
<?php
use Cake\Core\Configure;

return [
    // 定数の定義
    define("TEST","定数テスト"),
 
    // 変数の定義
    Configure::write("text1", "変数のテキスト"),

    Configure::write("auth_text", ["1" => "ユーザー","2" => "管理者"]),
];

これをbootstrap.phpで読み込む

config/bootstrap.php
try {
    Configure::config('default', new PhpConfig());
    Configure::load('app', 'default', false);
    Configure::load("const");// ここ
} catch (\Exception $e) {
    exit($e->getMessage() . "\n");
}

コントローラから使う

use Cake\Core\Configure;

を追加してから、

        $auth_text = Configure::read("auth_text");

テンプレートで画像を表示する

Template/Users/login.ctp
<?= $this->Html->image('bootstrap-solid.svg', ["width" => "72", "height" => "72"]) ?>

formにclassを追加

Template/Users/login.ctp
<?= $this->Form->create(false, ["class" => "form-signin"]) ?>

普通のインプット

    <?= $this->Form->control('name', ["type" => "text", "class" => "form-control", "required" => false, "label" => ["text" => "氏名"]]);?>

こんな感じで出力される。

<div class="input text">
    <label for="name">氏名</label>
    <input type="text" name="name" class="form-control" required="required" id="name">
</div>

validationエラーのときのメッセージのスタイルを変更

テンプレの上の方に入れておく。

<?php $myTemplates = [
    'error' => '<div class="text-danger">{{content}}</div>'
];
$this->Form->setTemplates($myTemplates);?>

ラジオボタン

<?= $this->Form->radio('sex', [['value' => '1', 'text' => '男'],['value' => '2', 'text' => '女']], ["class" => "form-check-input", "label" => ["class" => "form-check-label"]]);?>

validation

メールアドレスがユニークか

Model/Table/UsersTable.php
        $validator
            ->scalar('username')
            ->maxLength('username', 255)
            ->notEmpty('username', 'メールアドレスを入力してください。')
            ->add('username', 'validFormat', [
                'rule' => 'email',
                'message' => '正しいメールアドレスを入力してください。'
            ])
            ->add('username', 'unique', [
                'rule' => 'validateUnique',
                'provider' => 'table',
                'message' => 'このメールアドレスは既に使われています。'
            ]);

パスワード確認が一致しているか

Model/Table/UsersTable.php
        $validator
            ->scalar('password')
            ->maxLength('password', 255)
            ->notEmpty('password', 'パスワードを入力してください。')
            ->allowEmpty('password', 'update')
            ->add('password',[
                'compareWith' => [
                    'rule' => ['compareWith', 'password2'],
                    'message' => 'パスワードが一致しません'
                ]
            ]);

最初に開くページを変更する

アプリのルートディレクトリを開いた時にアクセスするページをログインページにしたい時、routes.phpの以下の部分を変更する。

config/routes.php
    //$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
    $routes->connect('/', ['controller' => 'Users', 'action' => 'login']);
5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?