shopping cart

Hi Friends!

I use yii2-shopping-cart by omnilight

I add to model




class Product extends ActiveRecord implements CartPositionInterface

{

    use CartPositionTrait;


    public function getPrice()

    {

        return $this->price;

    }


    public function getId()

    {

        return $this->id;

    }

}



add to controller:




public function actionAddToCart($id)

{

    $cart = new ShoppingCart();


    $model = Product::findOne($id);

    if ($model) {

        $cart->put($model, 1);

        return $this->redirect(['cart-view']);

    }

    throw new NotFoundHttpException();

}



But how to use it in view?


\Yii::$app->cart->put($cartPosition, 1);

And how to create add to cart button in view?

Try this extension

Easy, use ActiveForm with submit button executing your addCart controller. Pass $id of your item and quantity from your ActiveForm.


$form = ActiveForm::begin([

                    'id' => 'addCartForm-form',

                    'action' => ['your Add controller'],

                   

       ]);


.....here your inputs....




<?= Html::submitButton('Add to cart') ?>

Also you can use some ajax when user hit button (I use it to get current quantity of one product):


controller (cart):


public function actionGetquantity($id) {

        $cart = new ShoppingCart();


        $position = $cart->getPositionById($id);


        $liczba = $position->getQuantity();

        

        if ($liczba !== NULL) {

            $response = ['liczba' => $liczba, 'id' => $id];

            return \yii\helpers\Json::encode($response);

            

        } else {

            throw new Exception;

        }

    }


and jquery:


 $.ajax({

            url: 'your url....cart/getquantity',

            data: {

                id: id

            },

            type: 'GET',

            dataType: 'json',

            success: function(data) {


             ........your code.......


}