[SOLVED] Fatal error: Using $this when not in object ?

i am new user yii2… i have a problem when i go to views i get this error “Fatal error: Using $this when not in object context in D:\Web\MyWebs\laura\frontend\views\ge-tvipe\index.php on line 10”, but when i go to http://localhost/laura/frontend/web/index.php this works fine … help me pls sorry for my english i learn to write :D

i get the same error in all frontend\views …

Please post the code of your ge-tvipe index view and the ge-tvipe controller actionIndex method.

index




<?php


use yii\helpers\Html;

use yii\grid\GridView;


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

/* @var $searchModel app\models\GeTvipeSearch */

/* @var $dataProvider yii\data\ActiveDataProvider */


$this->title = 'Ge Tvipes';

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

?>

<div class="ge-tvipe-index">


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

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


    <p>

        <?= Html::a('Create Ge Tvipe', ['create'], ['class' => 'btn btn-success']) ?>

    </p>


    <?= GridView::widget([

        'dataProvider' => $dataProvider,

        'filterModel' => $searchModel,

        'columns' => [

            ['class' => 'yii\grid\SerialColumn'],


            'vipe_codi',

            'vinc_codi',

            'pers_auxi',


            ['class' => 'yii\grid\ActionColumn'],

        ],

    ]); ?>


</div>



view




<?php


use yii\helpers\Html;

use yii\widgets\DetailView;


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

/* @var $model app\models\GeTvipe */


$this->title = $model->vipe_codi;

$this->params['breadcrumbs'][] = ['label' => 'Ge Tvipes', 'url' => ['index']];

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

?>

<div class="ge-tvipe-view">


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


    <p>

        <?= Html::a('Update', ['update', 'id' => $model->vipe_codi], ['class' => 'btn btn-primary']) ?>

        <?= Html::a('Delete', ['delete', 'id' => $model->vipe_codi], [

            'class' => 'btn btn-danger',

            'data' => [

                'confirm' => 'Are you sure you want to delete this item?',

                'method' => 'post',

            ],

        ]) ?>

    </p>


    <?= DetailView::widget([

        'model' => $model,

        'attributes' => [

            'vipe_codi',

            'vinc_codi',

            'pers_auxi',

        ],

    ]) ?>


</div>



and my controller




<?php


namespace app\controllers;


use Yii;

use app\models\GeTvipe;

use app\models\GeTvipeSearch;

use yii\web\Controller;

use yii\web\NotFoundHttpException;

use yii\filters\VerbFilter;


/**

 * GeTvipeController implements the CRUD actions for GeTvipe model.

 */

class GeTvipeController extends Controller

{

    public function behaviors()

    {

        return [

            'verbs' => [

                'class' => VerbFilter::className(),

                'actions' => [

                    'delete' => ['post'],

                ],

            ],

        ];

    }


    /**

     * Lists all GeTvipe models.

     * @return mixed

     */

    public function actionIndex()

    {

        $searchModel = new GeTvipeSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


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

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }


    /**

     * Displays a single GeTvipe model.

     * @param integer $id

     * @return mixed

     */

    public function actionView($id)

    {

        return $this->render('view', [

            'model' => $this->findModel($id),

        ]);

    }


    /**

     * Creates a new GeTvipe model.

     * If creation is successful, the browser will be redirected to the 'view' page.

     * @return mixed

     */

    public function actionCreate()

    {

        $model = new GeTvipe();


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->vipe_codi]);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }


    /**

     * Updates an existing GeTvipe model.

     * If update is successful, the browser will be redirected to the 'view' page.

     * @param integer $id

     * @return mixed

     */

    public function actionUpdate($id)

    {

        $model = $this->findModel($id);


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->vipe_codi]);

        } else {

            return $this->render('update', [

                'model' => $model,

            ]);

        }

    }


    /**

     * Deletes an existing GeTvipe model.

     * If deletion is successful, the browser will be redirected to the 'index' page.

     * @param integer $id

     * @return mixed

     */

    public function actionDelete($id)

    {

        $this->findModel($id)->delete();


        return $this->redirect(['index']);

    }


    /**

     * Finds the GeTvipe model based on its primary key value.

     * If the model is not found, a 404 HTTP exception will be thrown.

     * @param integer $id

     * @return GeTvipe the loaded model

     * @throws NotFoundHttpException if the model cannot be found

     */

    protected function findModel($id)

    {

        if (($model = GeTvipe::findOne($id)) !== null) {

            return $model;

        } else {

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

        }

    }

}



i download the advanced application template so when i go to /localhost/advanced/frontend/views/site/ i get the same error

Do not put "views" in front of the controller name (in this case "site"). It goes: localhost/advanced/frontend/site/index. Here site is the name of site controller, and index is name of index view that belongs to that site controller.

To see your ge-tvipe index view go : localhost/laura/ge-tvipe/index (if you are using pretty url and htaccess), if not then it should be: localhost/laura/index.php?r=ge-tvipe/index , or something like that, I always use pretty url :D.

when i set http://localhost/laura/index.php?r=ge-tvipe/index i get this error

Not Found

The requested URL /laura/index.php was not found on this server.

and in all index of my views i get the same error “Fatal error: Using $this when not in object context in D:\Web\MyWebs\laura\frontend\views\ge-tvipe\index.php on line 10”, whit ge-tvipe and others files is the same :(

Sorry it is: localhost/laura/web/index.php?r=site%2Findex

You should use pretty url and htaccess. Inside your main.php config file ( in common/config/main.php ) , put this line of code to components array:




'urlManager' => [

    'enablePrettyUrl' => true,

    'showScriptName' => false,

],



Like:




'components' => [

    'cache' => [

        'class' => 'yii\caching\FileCache',

    ],

    'urlManager' => [

         'enablePrettyUrl' => true,

         'showScriptName' => false,

    ],

    // other config

], // components



And inside your advanced/web folder create .htaccess file ( you must use this dot in front of htaccess ), and put this code inside:




RewriteEngine on


# If a directory or a file exists, use the request directly

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

# Otherwise forward the request to index.php

RewriteRule . index.php



After this you will have nice and clean URLs like: localhost/advanced/web/frontend/site/index

1 Like

thx for pretty url, but still I have the same error :(

Fatal error: Using $this when not in object context in D:\Web\MyWebs\laura\frontend\views\ge-tvipe\index.php on line 10

Are you trying manually to visit that URL or you are pressing some link in your menu ? That url is not correct. It should not be frontend/views/ge-tvipe, it should be frontend/web/ge-tvipe, and not index.php, but only index.

So full url:


localhost/laura/frontend/web/ge-tvipe/index

i am trying manually, when i set localhost/laura/frontend/web/ge-tvipe/index i get new error

Unknown Class – yii\base\UnknownClassException

Unable to find ‘frontend\controllers\GeTvipeController’ in file: D:\Web\MyWebs\laura/frontend/controllers/GeTvipeController.php. Namespace missing?

Well do you have GeTvipeController or not ? What is the name of it ?

Yes GeTvipeController

i solved my friend … i need changue in my crontroller namespace app\controllers; for namespace frontend\controllers; thx for you help and your time :D

Your namespaces are wrong.

Change:

"namespace app\controllers" to "namespace frontend\controllers".

"use app\models\GeTvipe" to "use frontend\models\GeTvipe"

"use app\models\GeTvipeSearch" to "use frontend\models\GeTvipeSearch"

Of course if your GeTvipe and GeTvipeSearch models are located inside frontend/models folder…

Also I bet that your namespaces of your GeTvipe and GeTvipeSearch models are wrong too.

You will have to change their namespaces from:

"namespace app\models" to "namespace frontend\models".

When you are using Gii tool with advanced template, you need to ajust te namespaces. "app" namespace is root for basic template, for advanced template it is "frontend", "backend", "common" and so on…

Oh you posted while I was writting :D. Good, Im glad it is solved now :D

:D thx men :D

thanks now it works. the problem was i’m trying pretty url but i did not set it. @shoneZ89