Ngu ngơ học làm web (x23) - CakePHP2 - Link hình ảnh, Flash, Load theo vị trí

Tiếp theo của: Ngu ngơ học làm web (x22) - CakePHP2 – Chức năng tìm kiếm
-----

Phần 23. CakePHP2 – Link hình ảnh, Flash, Load theo vị trí


Xem (clip số 24e – chickenrainshop):

- Tạo link hình ảnh bằng helper (2":35)

- Gửi thông báo: thành công, thất bại (20":00)

- Cho trang web load lại đúng vị trí mình đã gửi comment (21":29)

Tạo một link bằng hình ảnh, sử dụng Html helper, ví dụ:

<?php echo $this->Html->link($this->Html->image($book['Book']['image']), '/'.$book['Book']['slug']); ?>

Tuy nhiên, dòng mã trên sẽ không xuất ra hình ảnh mà xuất ra mã html. Để sửa lỗi này, thêm thuộc tính escape = false cho hàm link, ví dụ:

<?php echo $this->Html->link($this->Html->image($book['Book']['image']), '/'.$book['Book']['slug'], ['escape' => false]); ?>


Sửa lại trang hiển thị thông tin chi tiết một quyển sách. Vì bảng books trong cơ sở dữ liệu lúc thiết kế chưa có trường pages, nên sẽ thêm vào.

Phần thông báo lỗi được sử dụng lại nhiều lần, nên sẽ tạo một element cho nó, ví dụ:

[View\Elements\errors.ctp]

<?php if (isset($errors)): ?>
            <div class="alert alert-danger">
                        <?php foreach ($errors as $error): ?>
                                    <?php echo $error[0]; ?>
                        <?php endforeach ?>
            </div>
<?php endif ?>

Vì đang sử dụng CakePHP 2.9.6, nên để hiển thị thông báo khi thêm comment vào cơ sở dữ liệu thành công hoặc thất bại ở trong view, sử dụng hàm sau:

<?php echo $this->Flash->render(); ?>

Ví dụ,

[View\Books\view.ctp]
<h4>Gửi nhận xét</h4>
<?php echo $this->element('errors'); ?>
<?php echo $this->Flash->render(); ?>
<?php echo $this->Form->create('Comment', ['url' => ['action' => 'add'], 'novalidate' => true, 'class' => 'comments form']); ?>

Để ý hàm $this->Flash->render(); sẽ hiển thị thông tin được thiết lập trước đó (trong controller) bằng hàm:

$this->Flash->success('Đã gửi nhận xét thành công!',
                                                                        ['params' =>
                                                                                    ['class' => 'alert alert-info']
                                                                        ]);

Hoặc:

$this->Flash->error(('Chưa gửi được. Vui lòng thử lại.'),
                                                                        ['params' =>
                                                                                    ['class' => 'alert alert-danger']
                                                                        ]);

Ví dụ,

[Controller\CommentsController.php action Add()]

public function add() {
                        if ($this->request->is('post')) {
                                    // pr($this->request->data); exit;
                                    $this->Comment->set($this->request->data);
                                    if ($this->Comment->validates()) {
                                                $this->Comment->create();
                                                if ($this->Comment->save($this->request->data)) {
                                                            $this->Flash->success('Đã gửi nhận xét thành công!',
                                                                        ['params' =>
                                                                                    ['class' => 'alert alert-info']
                                                                        ]);
                                                } else {
                                                            $this->Flash->error(('Chưa gửi được. Vui lòng thử lại.'),
                                                                        ['params' =>
                                                                                    ['class' => 'alert alert-danger']
                                                                        ]);
                                                }
                                    } else {
                                                $comment_errors = $this->Comment->validationErrors;
                                                $this->Session->write('comment_errors', $comment_errors);

                                    }
                                    $this->redirect($this->referer());
                        }
            }

Trong Elements\Flash, thêm hai element có tên là success.ctp và error.ctp với nội dung như sau:

<div class="<?= h($params['class']) ?>">
    <?= h($message) ?>
</div>

Khi tải lại một trang, muốn nó hiển thị đúng ở một ví trí nào đó, trong hàm redirect, thêm tham số chỉ ra vị trí cần hiển thị, ví dụ, [Controller\CommentsController.php action Add()] sửa lại một chút như sau:

$this->redirect($this->referer().'#nhan-xet');

[View\Books\view.ctp]

<div class="panel">
            <h4 class="panel-heading"><span class="glyphicon glyphicon-bookmark"> Chi tiết</span></h4>
            <div class="row">
                        <div class="col col-lg-3">
                                    <div class="book-thumbnail">
                                                <?php echo $this->Html->image($book['Book']['image']); ?>
                                    </div>
                        </div>
                        <div class="col col-lg-9">
                                    <div class="book-info chi-tiet">
                                                <h4><?php echo h($book['Book']['title']); ?></h4>
                                                <p>Tác giả:
                                                            <?php if (!empty($book['Writer'])): ?>
                                                                        <?php foreach ($book['Writer'] as $writer): ?>
                                                                                    <?php echo $this->Html->link($writer['name'], '/tac-gia/'.$writer['slug']); ?>
                                                                        <?php endforeach; ?>
                                                            <?php else: ?>
                                                                        Đang cập nhật!
                                                            <?php endif; ?>
                                                </p>
                                                <p>Nhận xét:
                                                            <?php echo $this->Html->link($book['Book']['comment_count'].' nhận xét', '#nhan-xet'); ?>
                                                </p>
                                                <p>Giá bìa:
                                                            <?php echo $this->Number->currency($book['Book']['price'],' VND',['places' => 0,'wholePosition' => 'after']); ?>
                                                </p>
                                                <p>Giá bán:
                                                            <span class="label label-danger">
                                                                        <?php echo $this->Number->currency($book['Book']['sale_price'],' VND',['places' => 0,'wholePosition' => 'after']); ?>
                                                            </span>
                                                </p>
                                                <button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-shopping-cart"></span> Thêm vào giỏ hàng</button>
                                    </div>
                        </div>
                        <div class="col col-lg-12 book-content">
                                    <h4>Giới thiệu:</h4>
                                    <p>
                                                <?php echo h($book['Book']['info']); ?>
                                    </p>
                                    <div class="col-lg-7">
                                                <table class="table table-striped table-bordered">
                                                            <thead>
                                                                        <tr>
                                                                                    <th colspan="2">Thông tin chi tiết</th>
                                                                        </tr>
                                                            </thead>
                                                            <tbody>
                                                                        <tr>
                                                                                    <td>Nhà xuất bản:</td>
                                                                                    <td><?php echo h($book['Book']['publisher']); ?></td>
                                                                        </tr>
                                                                        <tr>
                                                                                    <td>Ngày xuất bản:</td>
                                                                                    <td><?php echo h($book['Book']['publish_date']); ?></td>
                                                                        </tr>
                                                                        <tr>
                                                                                    <td>Số trang:</td>
                                                                                    <td><?php echo h($book['Book']['pages']); ?></td>
                                                                        </tr>
                                                            </tbody>
                                                </table>
                                    </div>
                        </div>
            </div>
</div>
<!-- sách liên quan -->
<div class="panel panel-success">
            <h4 class="panel-heading"><span class="glyphicon glyphicon-list-alt"></span> Sách liên quan</h4>
            <?php echo $this->element('book', ['books' => $relatedBooks]); ?>
</div>
<!-- Bình luận - nhận xét -->
<div id="nhan-xet" class="panel">
            <h4 class="panel-heading"><span class="glyphicon glyphicon-comment"></span> Nhận xét</h4>
            <div class="row">
                        <div class="col col-lg-10">
                                    <?php if (!empty($comments)): ?>
                                                <?php foreach ($comments as $comment): ?>
                                                            <p class="comment">
                                                                        <strong><?php echo $comment['User']['username']; ?>:</strong>
                                                                        <?php echo $comment['Comment']['content']; ?>
                                                            </p>
                                                <?php endforeach; ?>
                                    <?php else: ?>
                                                <p class="comment">Chưa có nhận xét!</p>
                                    <?php endif; ?>
                        </div>
            </div>
</div>
<!-- gửi nhận xét -->
<h4>Gửi nhận xét</h4>
<?php echo $this->element('errors'); ?>
<?php echo $this->Flash->render(); ?>
<?php echo $this->Form->create('Comment', ['url' => ['action' => 'add'], 'novalidate' => true, 'class' => 'comments form']); ?>
            <?php
                        echo $this->Form->input('user_id',
                                    [
                                                'type' => 'text',
                                                'value' => 1,
                                                'hidden' => true,
                                                'label' => '',
                                                'required' => false
                                    ]);
                        echo $this->Form->input('book_id',
                                    [
                                                'type' => 'text',
                                                'hidden' => true,
                                                'label' => '',
                                                'required' => false,
                                                'value' => $book['Book']['id']
                                    ]);
                        echo $this->Form->input('content', ['label' => '', 'rows' => 5, 'class' => 'col-lg-12']);
            ?>
            <?php echo $this->Form->button('Gửi', ['type' => 'submit', 'class' => 'pull-right btn btn-primary col-lg-3 send-button']); ?>

<?php echo $this->Form->end(); ?>
-----------
Cập nhật 28/5/2017
-----------
Xem thêm:
Tổng hợp các bài viết về Ngu ngơ học làm web