nowiko
nowiko

Reputation: 2567

Trying to get property on a non object Yii 1.1.15

I try to change Css file for CGridView widget, in my config/main.php:

'components' => array(
     'widgetFactory' => array(
         'widgets' => array(
            'CGridView' => array(
                'cssFile' => Yii::app()->request->baseUrl . '/css/gridview.css',
            ),
         ),
      ),
  ...

And I get warning:

Trying to get property on a non object /path_to_project/protected/config/main.php on line 79

How I can suppress this warning, and why I getting it, in when I using it in view files it all works.

P.S. Yes I can set display_errors ini set to false and message will dissapearm but I want get clearly with it. Thanks!

Upvotes: 1

Views: 273

Answers (1)

topher
topher

Reputation: 14860

The reason for the warning is that the CHttpRequest object Yii::app()->request has not been instantiated yet.

From the API page for CApplication:

CApplication will undergo the following lifecycles when processing a user request:

  1. load application configuration;
  2. set up error handling;
  3. load static application components;
  4. onBeginRequest: preprocess the user request;
  5. processRequest: process the user request;
  6. onEndRequest: postprocess the user request;

Starting from lifecycle 3, if a PHP error or an uncaught exception occurs, the application will switch to its error handling logic and jump to step 6 afterwards.

Your error is happening at the first step. As such, Yii's error handling has not been setup yet. The only option is to suppress this warning using the @ operator:

 'cssFile' => @Yii::app()->request->baseUrl . '/css/gridview.css',

HOWEVER

This is a terrible idea, since you are essentially hiding the error instead of fixing it.

If your views are being displayed correctly (no css errors), you can omit the Yii::app()->request->baseUrl and just use:

'cssFile' => '/css/gridview.css'

If you are experiencing errors, you can create a class in your components folder that extends CWidgetFactory and set any variables that depend on other components here e.g

class MyWidgetFactory extends CWidgetFactory {
    public function init() {
        parent::init();
        $this->widgets['CGridView']['cssFile'] = Yii::app()->request->baseUrl.'css/gridview.css';
    }
}

You will need to adjust your components to use this file:

'components' => array(
    'widgetFactory' => array(
        'class' => 'MyWidgetFactory'
    ...

Upvotes: 4

Related Questions