Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class CartController extends Controller
- {
- public function actionCheckout()
- {
- $this->render('checkout');
- }
- public function actionIndex()
- {
- $session_cart = Yii::app()->user->getState('cart');
- $products = array();
- foreach ($session_cart as $product_id => $quantity) $products[] = $product_id;
- $product_info = Product::model()->findAllByPk($products);
- $total_price = 0;
- $cart = array();
- foreach ($product_info as $product) {
- $product_id = $product->product_id;
- $cart[$product_id]['product_id'] = $product->product_id;
- $cart[$product_id]['title'] = $product->title;
- $cart[$product_id]['description'] = $product->description;
- $cart[$product_id]['price'] = $product->price;
- $cart[$product_id]['quantity'] = $session_cart[$product_id];
- $cart[$product_id]['total_price'] = round($session_cart[$product_id] * $product->price, 2);
- $total_price += $cart[$product_id]['total_price'];
- }
- $dataProvider = new CArrayDataProvider($cart, array(
- 'id' => 'product_id',
- 'sort' => array(
- 'attributes' => array(
- 'id', 'title', 'price',
- ),
- ),
- ));
- $this->render('index',
- array(
- 'dataProvider' => $dataProvider,
- 'total_price' => $total_price
- )
- );
- }
- public function actionAdd($product_id, $quantity)
- {
- $product_id = (int)$product_id;
- $quantity = (int)$quantity;
- $product_count = Product::model()->exists(
- 'product_id=:product_id AND is_available = 1',
- array(':product_id' => $product_id)
- );
- if ($product_count) {
- $cart = Yii::app()->user->getState('cart');
- if (isset($cart[$product_id])) {
- $cart[$product_id] += $quantity;
- } else {
- $cart[$product_id] = $quantity;
- }
- Yii::app()->user->setState('cart', $cart);
- }
- $this->redirect(array('cart/index'));
- }
- public function actionRemove($product_id)
- {
- $product_id = (int)$product_id;
- $cart = Yii::app()->user->getState('cart');
- if (isset($cart[$product_id])) {
- unset($cart[$product_id]);
- }
- Yii::app()->user->setState('cart', $cart);
- $this->redirect(array('cart/index'));
- }
- public function actionClear()
- {
- Yii::app()->user->setState('cart', array());
- $this->redirect(array('cart/index'));
- }
- }
- ?>
Add Comment
Please, Sign In to add comment