[Công nghệ Thông tin] -- [Web] -- [Công nghệ phần mềm] -- [PhoThong] -- [TỪ ĐIỂN] -- [----] -- [Học viên cũ] -- [10.000 giờ]
--------------- <> -----------------
---  KHOA HỌC - CÔNG NGHỆ - GIÁO DỤC - VIỆC LÀM ---
---  Nhận làm website, web app, chạy quảng cáo, digital marketing --->>>  LIÊN HỆ...

Tìm kiếm trong Blog

Hiển thị các bài đăng có nhãn cập nhật giỏ hàng. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn cập nhật giỏ hàng. Hiển thị tất cả bài đăng

Ngu ngơ học làm web (x27) - CakePHP2 - Cập nhật giỏ hàng (tt)

Tiếp theo của: Ngu ngơ học làm web (x26) - CakePHP2 – Xem, cập nhật giỏ hàng
-----

Phần x27. CakePHP2 – Cập nhật giỏ hàng (tt)


Xem (clip số 28 – chickenrainshop):
- escapse => false: để hiển thị nội dung html(7":07)

Viết đoạn mã cho nút “Làm rỗng giỏ hàng”, sử dụng một postLink ,
trong [View\Books\view_cart.ctp]:

<?php echo $this->Form->postLink('Làm rỗng giỏ hàng', '/books/emptyCart', ['class' => 'col-lg-3 btn btn-default empty']); ?>

Viết action emptyCart trong BooksController.php

public function emptyCart() {
                        if ($this->request->is('post')) {
                                    $this->Session->delete('cart');
                                    $this->Session->delete('payment');
                                    $this->redirect($this->referer());
                        }
            }

Viết chức năng xóa từng quyển sách.

Viết đoạn mã cho nút X, sử dụng một postLink,
trong [View\Books\view_cart.ctp]:

<?php echo $this->Form->postLink('<span class="glyphicon glyphicon-remove"></span>', '/books/remove/'.$book['id'], ['escape' => false]); ?>

Viết action remove trong BooksController.php

            public function remove($id = null) {
                        if ($this->request->is('post')) {
                                    $this->Session->delete('cart.'.$id);
                                    $cart = $this->Session->read('cart');
                                    if (empty($cart)) {
                                                $this->emptyCart();
                                    } else {
                                                $total = $this->Tool->arraySum($cart, 'quantity', 'sale_price');
                                                $this->Session->write('payment.total', $total);
                                    }
                                    $this->redirect($this->referer());
                        }
            }

Xem (clip số 29bt – chickenrainshop):

Viết chức năng cập nhật số lượng sách.

Nội dung của form cập nhật số lượng, trong [View\Books\view_cart.ctp]:

<?php echo $this->Form->create('Book', ['url' => ['action' => 'quantityUpdate']], ['class' => 'form-inline']) ?>
            <?php echo $this->Form->input('bookId', ['type' => 'hidden', 'value' => $book['id']]); ?>
            <?php echo $this->Form->input('quantity', ['value' => $book['quantity'], 'class' => 'col col-lg-2', 'label' => false, 'div' => false]); ?>
            <?php echo $this->Form->button('Cập nhật', ['class' => 'btn btn-link', 'type' => 'submit']); ?>
            <?php echo $this->Form->end(); ?>

Viết action quantityUpdate() trong controller BooksController.php:

Ý tưởng là:

- Khi gửi form lên thì gửi thêm trường bookId để biết được người dùng đã tăng số lượng của cuốn 
sách nào

- Dựa vào bookId, đọc cuốn sách tương ứng trong Session

- So sánh trường quantity do người dùng gửi lên ($newQuantity) và trường quantity đọc từ Session ($oldQuantity)

- Nếu giá trị người dùng gửi lên lớn hơn 0 và khác giá trị trước đó thì cập nhật lại trường quantity vào Session, đồng thời tính lại giá trị của trường Tổng tiền

- Tải lại trang hiện tại để cập nhật các giá trị mới

public function quantityUpdate() {
                        if ($this->request->is('post')) {
                                    $id = $this->request->data['Book']['bookId'];
                                    $book = $this->Session->read('cart.'.$id);
                                    $oldQuantity = $book['quantity'];
                                    $newQuantity = $this->request->data['Book']['quantity'];
                                    if ($newQuantity > 0 && $newQuantity != $oldQuantity) {
                                                $book['quantity'] = $newQuantity;
                                                $this->Session->write('cart.'.$id, $book);
                                                $cart = $this->Session->read('cart');
                                                $total = $this->Tool->arraySum($cart, 'quantity', 'sale_price');
                                                $this->Session->write('payment.total', $total);
                                    }
                        }
                        $this->redirect($this->referer());

            }
-----------
Cập nhật 1/6/2017
-----------
Xem thêm:
Tổng hợp các bài viết về Ngu ngơ học làm web

Ngu ngơ học làm web (x26) - CakePHP2 - Xem, cập nhật giỏ hàng

Tiếp theo của: Ngu ngơ học làm web (x25) - CakePHP2 – Tính tiền giỏ hàng, component
-----

Phần x26. CakePHP2 – Xem, cập nhật giỏ hàng


Xem (clip số 27b – chickenrainshop):

- set->(compact()) - gửi nhiều biến lên view (2":56)

- sử dụng layout khác thay thế cho layout default (10":10) 

Đoạn mã cho nút “Xem/Cập nhật giỏ hàng”:

Element [cart.ctp]

<p class="pricetotal"><span class="label">Tổng: <?php echo $this->Number->currency($total,
                                                ' VND', ['places' => 0, 'wholePosition' => 'after']); ?></span></p>
<?php echo $this->Html->link('Xem/Cập nhật giỏ hàng', '/gio-hang', ['class' => 'update-cart btn btn-primary btn-block']); ?>
<?php else: ?>

Vì giao diện bị bể, nên sẽ css một chút.

[chickenrainshop.css]

.update-cart {
    width: 200px;
    text-align: center;
    margin: 0 auto;
    margin-top: 40px;
}

Cấu hình route cho link $this->Html->link('Xem/Cập nhật giỏ hàng', '/gio-hang'):

[routes.php]

Router::connect('/sach-moi', ['controller' => 'books', 'action' => 'latest_books']);
Router::connect('/gio-hang', ['controller' => 'books', 'action' => 'viewCart']);
Router::connect('/tac-gia', ['controller' => 'writers', 'action' => 'index']);

Viết action viewCart trong [BooksController.php]

/*
* xem chi tiết giỏ hàng
*/
            public function viewCart() {
                        $cart = $this->Session->read('cart');
                        $payment = $this->Session->read('payment');
                        $this->set(compact('cart', 'payment'));
                        $this->set('title_for_layout', 'Giỏ hàng');
            }
           
            public function addToCart($id = null) {

Để gửi nhiều hơn một biến lên view, sử dụng hàm compact, ví dụ:

$this->set(compact('cart', 'payment'));

Viết view view_cart: do view view_cart sử dụng layout khác so với layout default, vì vậy cần phải tạo layout trước (layout cart.ctp).

Tạo layout mới, có tên là cart.ctp.

[Layouts\cart.ctp]

<!DOCTYPE html>
<html>
<head>
            <?php echo $this->Html->charset(); ?>
            <title>
                        <?php echo $title_for_layout; ?>
            </title>
            <?php
                        echo $this->Html->meta('icon');
                        echo $this->Html->css('bootstrap.min');
                        echo $this->Html->css('chickenrainshop');
                        echo $this->fetch('meta');
                        echo $this->fetch('css');
                        echo $this->fetch('script');
            ?>
</head>
<body>
            <div id="container" class="container">
                        <div id="header">
                                    <nav class="navbar navbar-default">
                                                <div class="navbar-header">
                                                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#mainmenu">
                                                <span class="sr-only">Toggle navigation</span>
                                                <span class="icon-bar"></span>
                                                <span class="icon-bar"></span>
                                                <span class="icon-bar"></span>
                                    </button>
                                    <a href="#" class="navbar-brand">Chickenrainshop</a>
                        </div>
                        <div class="navbar-collapse collapse" id="mainmenu">
                                    <ul class="nav navbar-nav">
                                    <li class="active"><?php echo $this->Html->link('Sách mới', '/sach-moi') ?></li>
                                    <li><a href="#ban-chay">Sách bán chạy</a></li>
                                    <li><a href="#lien-he">Liên hệ</a></li>
                                    </ul>
                                    <ul class="nav navbar-nav pull-right">
                                                <?php
                                                            echo $this->Form->create('Book', [
                                                                        'url' => ['action' => 'get_keyword'],
                                                                        'class' => 'navbar-form search'
                                                                        ]);
                                                            echo $this->Form->input('keyword',[
                                                                        'label' => '',
                                                                        'style' => 'width: 200px',
                                                                        'placeholder' => 'Tìm kiếm...'
                                                                        ]);
                                                            echo $this->Form->end();
                                                ?>

                                    </ul>
                        </div>
                                    </nav>
                        </div><!-- #header -->
                        <div id="content">
                                    <div class="row">
                                                <div class="content col col-lg-12">
                                                            <?php echo $this->fetch('content'); ?>
                                                </div><!-- content -->
                                    </div>
                        </div>
                        <div id="footer">
                                    <div class="container">
                                                <p class="text-muted pull-right">Học CakePHP2</p>
                                    </div>
                        </div>
            </div>
            <?php echo $this->Html->script('jquery'); ?>
            <?php echo $this->Html->script('bootstrap.min'); ?>
</body>
</html>

Để sử dụng layout cart vừa tạo ở trên, trong [BooksController.php action viewCart()] thêm dòng lệnh $this->layout= ‘cart’;

Ví dụ:

public function viewCart() {
                        $this->layout = 'cart';
                        $cart = $this->Session->read('cart');

[View\Books\view_cart.ctp]

<?php if ($this->Session->check('cart')): ?>
            <div class="panel">
                        <h4 class="panel-heading"><span class="glyphicon glyphicon-shopping-cart"></span>Giỏ hàng của bạn</h4>
                        <div class="row">
                                    <div class="chi-tiet-gio-hang">
                                                <table class="table table-striped">
                                                            <thead>
                                                                        <tr>
                                                                                    <th>STT</th>
                                                                                    <th>Tên sách</th>
                                                                                    <th>Số lượng</th>
                                                                                    <th>Giá</th>
                                                                                    <th>Xóa</th>
                                                                        </tr>
                                                            </thead>
                                                            <tbody>
                                                                        <?php $i = 1; ?>
                                                                        <?php foreach ($cart as $book): ?>
                                                                                    <tr>
                                                                                                <td><?php echo $i++; ?></td>
                                                                                                <td><?php echo $this->Html->link($book['title'], '/'.$book['slug']); ?></td>
                                                                                                <td class='row'>
                                                                                                <?php echo $this->Form->create('Book', ['class' => 'form-inline']) ?>
                                                                                                            <?php echo $this->Form->input('quantity', ['value' => $book['quantity'], 'class' => 'col col-lg-2', 'label' => false, 'div' => false]); ?>
                                                                                                            <?php echo $this->Form->button('Cập nhật', ['class' => 'btn btn-link', 'type' => 'submit']); ?>
                                                                                                <?php echo $this->Form->end(); ?>
                                                                                                </td>
                                                                                                <td><?php echo $this->Number->currency($book['sale_price'],' VND',['places' => 0,'wholePosition' => 'after']); ?>
                                                                                                </td>
                                                                                                <td><a href="#"><span class="glyphicon glyphicon-remove"></span></a></td>
                                                                                    </tr>
                                                                        <?php endforeach ?>
                                                                        <tr>
                                                                                    <td></td>
                                                                                    <td colspan="2"><strong>Tổng cộng</strong></td>
                                                                                    <td colspan="2"><strong><?php echo $this->Number->currency($payment['total'],' VND',['places' => 0,'wholePosition' => 'after']); ?></strong></td>
                                                                        </tr>
                                                                        <tr>
                                                                                    <td></td>
                                                                                    <td colspan="2"><strong>Đã giảm <small>(Coupon: CAKEPHP - giảm 10%)</small></strong></td>
                                                                                    <td colspan="2"><strong>0 VND</strong></td>
                                                                        </tr>
                                                                        <tr class="success">
                                                                                    <td></td>
                                                                                    <td colspan="2"><h4><strong>Giá phải trả</strong></h4></td>
                                                                                    <td colspan="2"><h4><span class="label label-danger"><?php echo $this->Number->currency($payment['total'],' VND',['places' => 0,'wholePosition' => 'after']); ?></span></h4></td>
                                                                        </tr>
                                                            </tbody>
                                                </table>
                                    </div>
                                    <button type="submit" class="col-lg-3 btn btn-default empty">Làm rỗng giỏ hàng</button>
                        </div>
            </div>

<?php else: ?>
            <div class="panel">
                        Giỏ hàng đang rỗng.
                        Quay về <?php echo $this->Html->link('trang chủ', '/'); ?> để thêm quyển sách vào giỏ hàng.
            </div>
<?php endif ?>

Thêm đoạn mã sau vào chickenrainshop.css:

.chi-tiet-gio-hang {
    width: 800px;
    margin: 0 auto;
}

.empty {
    margin-left: 30px;
    background: #C0C0C0;
    color: #FFF;

}
-----------
Cập nhật 31/5/2017
-----------
Xem thêm:
Tổng hợp các bài viết về Ngu ngơ học làm web