1

I have a module with a console controller (ScriptsController):

namespace modules\vetscripts\console\controllers;

use yii\console\Controller;
use yii\console\ExitCode;
use modules\vetscripts\VetScripts;

class ScriptsController extends Controller
{
    public function actionExpiring()
    {
        VetScripts::$instance->scripts->expiringScripts();

        return ExitCode::OK;
    }
}

When I run it using $ ./craft vetscripts/scripts/expiring I get the following error and stack trace:

2019-08-05 11:35:24 [-][-][-][error][yii\base\UnknownMethodException] yii\base\UnknownMethodException: Calling unknown method: craft\console\Request::getAcceptsJson() in /Users/steven/Code/vetscripts/vendor/yiisoft/yii2/base/Component.php:300
Stack trace:
#0 /Users/steven/Code/vetscripts/vendor/craftcms/cms/src/web/Controller.php(189): yii\base\Component->__call('getAcceptsJson', Array)
#1 /Users/steven/Code/vetscripts/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('expiring', Array)
#2 /Users/steven/Code/vetscripts/vendor/yiisoft/yii2/console/Application.php(180): yii\base\Module->runAction('vetscripts/scri...', Array)
#3 /Users/steven/Code/vetscripts/vendor/craftcms/cms/src/console/Application.php(93): yii\console\Application->runAction('vetscripts/scri...', Array)
#4 /Users/steven/Code/vetscripts/vendor/yiisoft/yii2/console/Application.php(147): craft\console\Application->runAction('vetscripts/scri...', Array)
#5 /Users/steven/Code/vetscripts/vendor/yiisoft/yii2/base/Application.php(386): yii\console\Application->handleRequest(Object(craft\console\Request))
#6 /Users/steven/Code/vetscripts/craft(22): yii\base\Application->run()
#7 {main}

This is my first time attempting a custom console command, which I need to get a cron job up and running. Is there something I'm missing here?

Thanks!

1

I had a hunch that a web controller with a similar name was getting called, and indeed that is what was happening. In my module's init method I was setting the controller namespace like this:

$this->controllerNamespace = 'modules\vetscripts\controllers';`

By default, then, the console was going to the web controller, I'm assuming. @Selvin pointed me in the right direction with this:

use craft\console\Application as Console

...

public function init()
{
    ...
    if (Craft::$app instanceof Console) {
        $this->controllerNamespace = 'modules\vetscripts\console\controllers';
    }
    ...
}

Now I can see my module's custom console actions when running ./craft from the console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.