I have controller
public function actionIndex()
{
$rows = Players::find()->all();
return $this->render('index', [
'rows' => $rows
]);
}
and view
<h1><?=$listPlayer -> name?></h1>
Error = Undefined variable ‘$listPlayer’
I re-read all the documentation and all the guides on the Internet and it works for everyone. Except me
UPD
Controller
public function actionIndex()
{
$rows = Players::find()->all();
return $this->render('index', [
'rows' => $rows
]);
}
view
<?php foreach ($rows as $listPlayer): ?>
<h1><?= $listPlayer->name ?></h1>
<?php endforeach; ?>
2
Answers
The error you’re encountering, "Undefined variable ‘$listPlayer’", indicates that you’re trying to access a variable called
$listPlayer
in your view, but it hasn’t been defined or passed from your controller. In your controller, you’re passing a variable called$rows
to your view, not$listPlayer
.To fix this issue, you should use the variable name that you passed from your controller, which is
$rows
. Here’s how you should update your view:In the above code, we’re using a
foreach
loop to iterate through the$rows
array, which contains yourPlayers
records. For each$listPlayer
in the loop, we can access itsname
property.First of all:
<h1><?=$listPlayer -> name?></h1>
– hit some spaces between opening/closing tags (if you pasted as it is).Second: define
$listPlayer
. There isn’t any variable $listPlayer in your action. You have only $rows. Rows, I asume – has a list of players, if you need a list (…->all()
).