Wednesday, March 9, 2022

[FIXED] Yii2: Stand alone Action in Module

Issue

I want to create a directory tree like this:

  • models
  • modules
    • help
      • controllers
        • default
          • IndexAction.php
        • DefaultController.php
      • views
        • default
          • index.php
      • help.php

So that if I call localhost/mysite/web/index.php?r=help/default/index I should get the index view.

So I created a module withe gii. My Module Class is "app\modules\help\help". I had to use help twice so that I get my module in a subdirectory. ( This is something I don't get. Why doesn't create Yii an subdirectory for each module?)

In the next step I created my Stand Alone Action

<?php
namespace app\modules\help\controllers;

use yii\base\Action;

class IndexAction extends Action
{

    public function run()
    {
        $this->controller->render('index');
    }

}

In the next step I modified my Controller to use the stand alone action

<?php

namespace app\modules\help\controllers;

use yii\web\Controller;

class DefaultController extends Controller
{

    public function actions()
    {
        return [
            'index'    => 'app\modules\help\controllers\default\IndexAction',
        ];
    }

}

If I call now my view in the browser I get the following error:

Unknown Class – yii\base\UnknownClassException
Unable to find 'app\modules\help\controllers\default\IndexAction' in file: E:\wamp\www\my_website/modules/help/controllers/default/IndexAction.php. Namespace missing?

But if I go to this Path E:\wamp\www\my_website/modules/help/controllers/default/ on my pc I get shown the IndexAction.php Can someone help me?

The stand alone action is in a subdirectory of controllers. So the namespace schould be

namespace app\modules\help\controllers\default;

But that causes this error:

 PHP Parse Error – yii\base\ErrorException
 syntax error, unexpected 'default' (T_DEFAULT), expecting identifier (T_STRING)

EDIT

If I use this namespace app\modules\help\controllers\IndexAction in the IndexAction.php I get the following Error. Even if I change the route in the controller I get the unknownClassException:

Unknown Class – yii\base\UnknownClassException
Unable to find 'app\modules\help\controllers\default\IndexAction' in file: E:\wamp\www\my_website/modules/help/controllers/default/IndexAction.php. Namespace missing?

And if I use this namespace app\modules\help\controllers\default in the IndexAction.php I get this:

 PHP Parse Error – yii\base\ErrorException
 syntax error, unexpected 'default' (T_DEFAULT), expecting identifier (T_STRING)

Solution

As D.Mill says in his comment. default is a reserved keyword. I had to rename the directory and it now works quite fine.



Answered By - EvilKarter

No comments:

Post a Comment

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