D
D
darknet372017-03-17 09:41:38
Yii
darknet37, 2017-03-17 09:41:38

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
      ];
    }
  }
}

In the product card, it is displayed like this:
<?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;?>

The form in the product card:
10e108d5e7da44f18a4a2ad50105ca43.png
When the order button is clicked, the data should go to the cart, how can I get this data in the cart?
If you do as it is currently written in the ELSE block, then each value is a separate field, and I have one field and it contains an associative array.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Timofeev, 2017-03-17
@darknet37

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));
    }

R
Rsa97, 2017-03-17
@Rsa97

unserialize()

I
Immortal_pony, 2017-03-17
@Immortal_pony

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 question

Ask a Question

731 491 924 answers to any question