Answer the question
In order to leave comments, you need to log in
Specifying the number of items added to the cart - how to do it?
I'll start with a picture to make it clearer.
I'm trying to specify what quantity to add to the cart, but the entire quantity is indicated only for the first product. If the first item has a quantity of 4, and the third has 1 and added the third, then 4 pieces will still be added to the third product.
How to specify the quantity by the desired product id?
- - -
Code:
View
<?php foreach ($pizza as $one): $i++?>
<input type="text" value="1" id="qty">
<a href="<?= \yii\helpers\Url::to(['cart/add', 'id' => $one->id]) ?>" data-id="<?= $one->id ?>" type="submit" class="product__button button button_primary-outline add-to-cart">
<span class="button__inc">В корзину</span>
</a>
<?php endforeach; ?>
$('.add-to-cart').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id'),
qty = $('#qty').val();
$.ajax({
url: '/cart/add',
data: {id: id, qty: qty},
type: 'GET',
success: function(res){
if(!res) alert('Ошибка!');
showCart(res);
},
error: function(){
alert('Error!');
}
});
});
public function actionAdd(){
$id = Yii::$app->request->get('id');
$qty = (int)Yii::$app->request->get('qty');
$qty = !$qty ? 1 : $qty;
$product = Product::findOne($id);
if(empty($product)) return false;
$session =Yii::$app->session;
$session->open();
$cart = new Cart();
$cart->addToCart($product, $qty);
if( !Yii::$app->request->isAjax ){
return $this->redirect(Yii::$app->request->referrer);
}
$this->layout = false;
return $this->render('cart-modal', compact('session'));
}
Answer the question
In order to leave comments, you need to log in
<input type="text" value="1" class="js-qty" id="qty">
qty = $(this).prev('.js-qty').val();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question