0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CakePHP画像表示について

Posted at

※DBは作成済とします。

※ユーザー情報を保存するUsersテーブルと投稿内容を保存するPostsテーブルとユーザー画像を保存するためのUploadsテーブルを使用しています。

作成物としてはdb内に保存されているデータを取り出しViewで表示する。

表示するものは、

・ユーザー画像

・ユーザー名

・メールアドレス

・紹介文

上記の内容を表示するページを作っていきましょう。

View/Users/view.ctp

<div class="user_view">
<h1>
<!-- dbからfile_nameを取得する -->
<?php $path = $user['Upload']['file_name']; ?>
<?php echo $this->Form->create('User'); ?>
<!-- file_nameの有無を判定する -->
<?php if ($path) : ?>
<!-- 取得したfile_nameを表示 -->
<?php echo $this->Html->image('/files/' . $path, array('alt' => 'user_image', 'width' => '100', 'height' => '100')); ?>
<?php else : ?>
<?php echo 'ユーザー画像:未登録'; ?>
<?php endif; ?>
<h1>ユーザー名:<?php echo $user['User']['username']; ?></h1>
<h1>メールアドレス:<?php echo $user['User']['mailaddress']; ?></h1>
<h1>一言コメント:
<?php $comment = $user['User']['comment']; ?>
<?php if ($comment) : ?>
<?php echo $comment; ?>
<?php else : ?>
<?php echo '未登録'; ?>
<?php endif; ?>
</h1>
</div>

User hasOne Uploadでユーザー情報を取得

user_idが一致する画像を取得するため$user['Upload']['file_name'];でuploadsテーブルからfile_nameを取り出す。

条件分岐にかけ画像を表示する。

$this->Html->image('/files/' . $path, array('alt' => 'user_image', 'width' => '100', 'height' => '100'));

上記文章を指定することで、以下が出力されます。

<img src="/img/cake/files/file_name.jpg" alt="user_image" width="100" height="100" />

 optionでは他に設定可能なのでググると必要な情報が出てくると思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?