Answer the question
In order to leave comments, you need to log in
How to get in the controller a value from another controller in which an associative array is displayed from the database?
I am writing an online store, and in the Model:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Cart extends ActiveRecord
{
public static function addToCart($product, $qty = 1)
{
if(isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]['qty'] += $qty;
}
else {
$_SESSION['cart'][$product_id] = [
'qty' => $qty,
'name' => $product->name,
'price' => $product->price,
'img' => $product->img
];
}
}
}
<?php foreach ($pr as $k => $v): ?>
<span><?php echo "Размер: ".$k; ?></span><br>
<span><?php echo "Цена: ".$v; ?></span><br>
<input type="text" name="quentity" value="1"><br>
<a href="<?php echo Url::to(['cart/add','id' => $product->product_id]);?>"
data-id="<?php echo $product->product_id ?>"
data-price="<?php echo $v ?>"
data-size="<?php echo $k ?>"
data-qty="1"
class="add-to-cart">Заказать
</a><br><br>
<?php endforeach;?>
Answer the question
In order to leave comments, you need to log in
serialize() and unserialize() are very tricky things, and at some point I promised myself never to use them again. There is JSON for this. And in yii there is a convenient helper:
www.yiiframework.com/doc-2.0/yii-helpers-json.html
You also work with the session bypassing yii, which in my opinion is not true.
Here is an example of your logic:
public static function addToCart($product, $qty = 1)
{
if($cart = Yii::$app->session->has('cart')) {
$cart = Json::decode($cart);
$cart[$product_id]['qty'] += $qty;
} else {
$cart[$product_id] = [
'qty' => $qty,
'name' => $product->name,
'price' => $product->price,
'img' => $product->img
];
}
Yii::$app->session->set('cart',Json::encode($cart));
}
unserialize()
And more.
First, Yii has a session wrapper .
Secondly, there are ready-made store components for Yii. From one of the Yii developers , for example.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question