Hello! I try to make something like a shopping cart, but i have the error from the title.
This is my controller, i suppose i did something wrong on the findBook function, but i don’t see what it is.
<?php
namespace frontend\modules\library\controllers;
use Yii;
class BookcollectionController extends \yii\web\Controller
{
public $totalBooks = 0;
public function actionAdd($id = null)
{
if (!intval ($id) || empty ($id)){
Yii::$app->session->setFlash('error', 'Cannot find this book');
return $this->redirect(['/library']);
}
if(!isset(Yii::$app->session['bookcollection'])) {
//nicio colectie creata
Yii::$app->session['bookcollection'] = [];
Yii::$app->session['total_books'] = 0;
}
$this->addtobookcollection($id);
return $this->redirect(['index']); //ma intorc la index, de modificat sa ma intorc la carte pe care eram
}
public function addtobookcollection($id)
{
if (isset(Yii::$app->session['bookcollection'] [$id])){ //daca exista prdusul adauga 1
$session = Yii::$app->session['bookcollection'];
$session[$id] = $session[$id] +=1;
Yii::$app->session['bookcollection'] = $session;
}else {// daca produsul nu exista, ramane la 1
$session = Yii::$app->session['bookcollection'];
$session[$id] = 1;
Yii::$app->session['bookcollection'] = $session;
}
}
public function setTotal()
{
Yii::$app->session['total_books'] = $this->totalBooks(Yii::$app->session['bookcollection']);
$this->totalBooks = Yii::$app->session['total_books'];
}
public function totalBooks($bookcollection)
{
$totalBooks = 0;
if(is_array($bookcollection)) {
foreach ($bookcollection as $id => $qty) {
$totalBooks += $qty;
}
return $totalBooks;
}
}
public function findBook($id)
{
return Book::findOne($id);
}
public function updateCollection()
{
foreach (Yii::$app->session['bookcollection'] as $id => $qty) {
if(isset($_POST[$id])) {
if($_POST[$id] == 0){
$session = Yii::$app->session['bookcollection'];
unset ($session[$id]);
Yii::$app->session['bookcollection'] = $session;
} else {
$bookcollection = Yii::$app->session['bookcollection'];
$bookcollection[$id] = $_POST[$id];
Yii::$app->session['bookcollection'] = $bookcollection;
}
}
}
}
public function actionIndex()
{
if(!isset(Yii::$app->session['bookcollection']) || empty(Yii::$app->session ['bookcollection'])) {
Yii::$app->session->setFlash('error', 'Empty collection');
return $this->redirect (['site/index']);
}
$this->updateCollection();
$this->setTotal();
return $this->render('/bookcollection/index');
}
}
The foreach code from the module index:
<?php foreach(Yii::$app->seassion['bookcollection'] as $id => $qty) {
$book = $this->context->findBook($id);
}
?>
I know i will look lazy, but i can’t see what i am doing wrong. Any tips?