skip to Main Content

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


  1. 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:

    <?php foreach ($rows as $listPlayer): ?>
        <h1><?= $listPlayer->name ?></h1>
    <?php endforeach; ?>
    

    In the above code, we’re using a foreach loop to iterate through the $rows array, which contains your Players records. For each $listPlayer in the loop, we can access its name property.

    Login or Signup to reply.
  2. 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()).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search