PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 26, 2022

[FIXED] Trying to get propertyof non-object yii

 February 26, 2022     php, yii, yii2     No comments   

Issue

I am starting to learn Yii framework so I am a beginner. I am struggling. I want to fetch the data from database using yii2 framework. This is my controller

 public  function actionView()
{


    $this->view->title = 'List Hotels';
    $items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');

        return $this->render('index', [
            'items' => $items,


        ]);

}

In my view file, I used the fetched data as below;

   <?php

/* @var $this yii\web\View */

use yii\helpers\Html;

 $this->title = 'Hotel list';
 $this->params['breadcrumbs'][] = $this->title;
 ?>

<?php foreach ($items as $item): ?>

<p> <?= $item-> name ?></p>
<p> <?= $item->address ?></p>
<p> <?= $item->description ?></p>


<?php endforeach; ?>

When I wrote var_dumps($items) under $items I can see the datas. However in the view It says Trying to get property 'name' of non-object. What did I wrong here please guide me. THanks for your time.


Solution

ArrayHelper::map()

Returns an array where, in your case, second argument passed is a key, the third is a value. So you need to access its elements as an array elements instead of class properties. Like:

<?php foreach ($items as $key => $value): ?>

    <p> <?= $key ?></p>
    <p> <?= $value ?></p>

<?php endforeach; ?>

More details here: https://www.yiiframework.com/doc/api/2.0/yii-helpers-basearrayhelper#map()-detail

But if you need to access data as class properties change the line in your controller:

$items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');

to:

$items = Hotel::find()->all();


Answered By - neolodor
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing