Trying to get property 'Stato' of non-object

Hello i have this problem in my view page with the function inline within the GridView. i post to you my controller action, my view and the error. Can anyone help me? I must use ‘contentOptions’ or ‘rowOptions’? I’m stucked in this problem. Thanks in advance!

code that is not working in the view:

<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\ActionColumn;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\data\ActiveDataProvider;
use app\controllers\SiteController;
use app\models\MElettrico;
/* @var $this yii\web\View *
/* @var $model app\models\MElettrico*/
/* @var $searchModel app\models\CRUDSearch */
/* @var $dataProvider yii\data\ActiveDataProvider*/

$this->title = 'M Elettricos';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="melettrico-index" align="left">
<script type="text/javascript">
      function colore(){
      var table = document.getElementById('MTable');
      var row = document.getElementsByTagName('tr');//da lenghth = 2 fino a lenghth -1
      console.log(row[2][3]);
      /*for (var i = 2; i < row.length -1; i++) {
          row[i] =
      }*/

      }
</script>
    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?php
        $model = new MElettrico();
        $admin= false;
        $normal= false;
        $onlyView = false;
        $user_logged = Yii::$app->session->get('__id');
        $permessi = SiteController::UserPermissions();
      //  $permessi =Yii::$app->session->get('permessi');
        $adminPermissions = $permessi['admin'];
        $normalPermissions = $permessi['normal'];
        $onlyViewPermissions = $permessi['only_view'];
        $adminUsers = explode(',',$adminPermissions);
        $normalUSers = explode(',',$normalPermissions);
        $onlyViewUsers = explode(',',$onlyViewPermissions);
        for ($i=0; $i <count($adminUsers); $i++) {
          if ($adminUsers[$i] == $user_logged) {
             $admin = true;
          }
        }
        if(! $admin){
        for ($i=0; $i <count($normalUSers); $i++) {
          if ($normalUSers[$i] == $user_logged) {
             $normal = true;
          }
        }
        if(!$normal){
              for ($i=0; $i <count($onlyViewUsers); $i++) {
                    if ($onlyViewUsers[$i] == $user_logged) {
                    $onlyView = true;
                  }
                }
              }
        }
        if(!$onlyView){
        ?>
        <?= Html::a('Create M Elettrico', ['create'], ['class' => 'btn btn-success']) ?>
      <?php } ?>
    </p>

    <?php Pjax::begin(); ?>
    <?php // echo $this->render('_search', ['model' => $searchModel]);

        if($admin){
    ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'id' => 'elementiMagazzino',
       'tableOptions' => [
          'id' => 'MTable',
          'class'=>"table table-striped table-bordered"
        ],
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            //'QRCode',
          /*  [
              'class' => 'yii\grid\DataColumn',
              'value' => function(){
                echo '<img src="' $dataProvider-> '">';
              }
            ],*/

            [
              'attribute' => 'Stato',
              'contentOptions' => function ($model){
                  if($model->Stato == 'Da Ordinare'){
                    return ['style' => 'background-color:Red'];
                  }
                  else if ($model->Stato =='Arrivato'){
                     return ['style' => 'background-color:Orange'];
                   }
                   else if ($model->Stato =='Scaffale'){
                     return ['style' => 'background-color:Yellow'];
                   }
                   else if ($model->Stato=='Montato'){
                     return ['style' => 'background-color:Green'];
                   }

                    return ['style' => 'background-color:White'];
                  }

            ],
            'Codice_Interno',
            'ID_Commessa',
            'Quantita',
            'Codice_Fornitore:ntext',
            'Descrizione:ntext',
            'Fornitore:ntext',
            'Marca:ntext',
            'QE_QB:ntext',
            'Costo',
            'Sconto_Base',
            'Sconto_Extra_1',
            'Sconto_Extra_2',
            'Costo_TotaleXQty_and_Sconto',
            'Tempi_Consegna',
            'Nome_Sullo_Schema:ntext',
            'Stazione_Appartenenza:ntext'


        ],
    ]); ?>

  <?php }
  else {?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            //'QRCode',
          /*  [
              'class' => 'yii\grid\DataColumn',
              'value' => function(){
                echo '<img src="' $dataProvider-> '">';
              }
            ],*/

            'Stato',
            'Codice_Interno',
            'ID_Commessa',
            'Quantita',
            'Codice_Fornitore:ntext',
            'Descrizione:ntext',
            'Fornitore:ntext',
            'Marca:ntext',
            'QE_QB:ntext',
            'Tempi_Consegna',
            'Nome_Sullo_Schema:ntext',
            'Stazione_Appartenenza:ntext'


        ],
    ]); ?>
<?php  }
  Pjax::end(); ?>

</div>

Controller

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\CRUDSearch;
use app\models\CRUDSearchCommesse;
use app\models\MElettrico;
use Da\QrCode\QrCode;
use app\models\Commesse;
use yii\db\Query;
use yii\data\ActiveDataProvider;
use yii\helpers\Url;

class SiteController extends Controller
{

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public static function UserPermissions(){
      return [
        'admin' => '100,103',
        'normal' => '101',
        'only_view' =>'102'
      ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
      Yii::$app->session->set('permessi', $this->UserPermissions());
        return $this->render('index');
    }

    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
      if ($model->load(Yii::$app->request->post()) && $model->login()) {

        return $this->goBack();
        }

        $model->password = '';
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    /**
     * Logout action.
     *
     * @return Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
    public function actionCrud(){
      $searchModel = new CRUDSearchCommesse();
      $dataProvider = $searchModel->search($this->request->queryParams);

      return $this->render('commesse', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
      ]);
    }
    /**
     * Displays contact page.
     *
     * @return Response|string
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

    /**
     * Displays about page.
     *
     * @return string
     */
    public function actionAbout()
    {
        return $this->render('about');
    }


    public function actionCreate(){
      $model = new MElettrico();
      $searchModel = new CRUDSearch();
      $dataProvider = $searchModel->search($this->request->queryParams);
      if ($this->request->isPost) {
          if ($model->load($this->request->post())){
          /*  if($this->request->post('QE_QB') == 1)
              $model->QE_QB = 'QE';
            else
              $model->QE_QB = 'QB';
*/
          //  $model->StringaToDate(Yii::$app->request->post('Tempi_Consegna'));

          $qrCode = (new QrCode('http://192.168.0.47:8080/index.php?r=site%2Fobject&Codice_Interno='.$model->Codice_Interno))
              ->setSize(75)
              ->setMargin(5)
              ->useForegroundColor(51, 153, 255);
          $qrCode->writeFile('C:/Users/carlo.lazzari/Desktop/prova/QRCodes/' .$model->Nome_Sullo_Schema. '.jpg');
          $model->save();

          }
          return $this->render('magazzinoElettrico', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
          ]);
        }
      return $this->render('create', [
          'model' => $model,
      ]);
    }

    public function actionCreazione(){
      $model = new Commesse();
      $searchModel = new CRUDSearchCommesse();
      $dataProvider = $searchModel->search($this->request->queryParams);
     if ($this->request->isPost && $model->load($this->request->post())) {
            $model->save();
            return $this->render('commesse', [
              'searchModel' => $searchModel,
              'dataProvider'=> $dataProvider,
            ]);
          }
      return $this->render('creazione', [
          'model' => $model,
      ]);
    }

    public function actionMagazzino($ID_Commessa){
      $model = new MElettrico();
      $searchModel = new CRUDSearch();
      $query = (new Query())->from('m_elettrico')
      ->where(['ID_Commessa' => $ID_Commessa]);
      Yii::$app->session->set('Commessa', $ID_Commessa);
      $dataProvider = new ActiveDataProvider([
        'query' => $query
      ]);
      return $this->render('magazzinoElettrico', [
        'model' => $model,
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
      ]);



    }

    public function actionObject($Codice_Interno){

      $model = new MElettrico();
      $model = $this->findModel($Codice_Interno);

      Yii::$app->session->set('Codice_Interno',$Codice_Interno);
      Yii::$app->user->setReturnUrl(Yii::$app->request->url);

    return $this->render('viewObject', [
      'model'=> $model
    ]);
    }

    public function actionArrivato(){
      $model = $this->findModel(Yii::$app->session->get('Codice_Interno'));
      $model->Stato = 'Arrivato';
      $model->save();

      $query = (new Query())->from('m_elettrico')
      ->where(['ID_Commessa' => $model->ID_Commessa]);
        $dataProvider = new ActiveDataProvider([
          'query'=> $query
        ]);
        $searchModel = new CRUDSearch();

        return $this->render('magazzinoElettrico', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
        ]);
    }
    public function actionScaffale(){
      $model = $this->findModel(Yii::$app->session->get('Codice_Interno'));
      $model->Stato = 'Scaffale';
      $model->save();

      $query = (new Query())->from('m_elettrico')
      ->where(['ID_Commessa' => $model->ID_Commessa]);
        $dataProvider = new ActiveDataProvider([
          'query'=> $query
        ]);
        $searchModel = new CRUDSearch();

        return $this->render('magazzinoElettrico', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
        ]);
    }

    public function actionMontato(){
      $model = $this->findModel(Yii::$app->session->get('Codice_Interno'));
      $model->Stato = 'Montato';
      $model->save();

      $query = (new Query())->from('m_elettrico')
      ->where(['ID_Commessa' => $model->ID_Commessa]);
        $dataProvider = new ActiveDataProvider([
          'query'=> $query
        ]);
        $searchModel = new CRUDSearch();

        return $this->render('magazzinoElettrico', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Finds the Commesse model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $ID_Commessa Id Commessa
     * @return Commesse the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($Codice_Interno)
    {
        if (($model = MElettrico::findOne(['Codice_Interno' => $Codice_Interno])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

YII Error on the browser

Hi @Carlone22, welcome to the forum.

Does your code work as expected if you comment out the contentOptions part?

[
    'attribute' => 'Stato',
    /* 'contentOptions' => function ($model){
          if($model->Stato == 'Da Ordinare'){
              return ['style' => 'background-color:Red'];
          } else if ($model->Stato =='Arrivato'){
              return ['style' => 'background-color:Orange'];
          } else if ($model->Stato =='Scaffale'){
              return ['style' => 'background-color:Yellow'];
          } else if ($model->Stato=='Montato'){
              return ['style' => 'background-color:Green'];
          }
          return ['style' => 'background-color:White'];
    } */
],

Hi softark,
thanks for welcoming me .
No it’s not coloring the background but it works properly. This error spawn because i want to access at the model in the line to control different value to color this field with diffierent colors.

Try model[index]->Stato (also modify the signature)

    /**
     * Renders a data cell.
     * @param mixed $model the data model being rendered
     * @param mixed $key the key associated with the data model
     * @param int $index the zero-based index of the data item among the item array returned by [[GridView::dataProvider]].
     * @return string the rendering result
     */
    public function renderDataCell($model, $key, $index)
    {
        if ($this->contentOptions instanceof Closure) {
            $options = call_user_func($this->contentOptions, $model, $key, $index, $this);
        } else {
            $options = $this->contentOptions;
        }

        return Html::tag('td', $this->renderDataCellContent($model, $key, $index), $options);
    }

Your controller have too much methods. I suggest you remove irrelevant methods!
Until then check If you are not calling asArray() anywhere in data provider Query

Ah, so $model['Stato'] might work, I guess.

[
    'attribute' => 'Stato',
    'contentOptions' => function ($model, $key, $index){
          if($model['Stato'] == 'Da Ordinare'){
              return ['style' => 'background-color:Red'];
          } else if ($model['Stato'] =='Arrivato'){
              return ['style' => 'background-color:Orange'];
          } else if ($model['Stato'] =='Scaffale'){
              return ['style' => 'background-color:Yellow'];
          } else if ($model['Stato']=='Montato'){
              return ['style' => 'background-color:Green'];
          }
          return ['style' => 'background-color:White'];
    } 
],

It perfectly work! thanks so much to every one for the advices!

1 Like