Tino Fernández
Tino Fernández

Reputation: 108

Check if an arbitrary controller/action exist

Is there are any way to check if an arbitrary combination of controller/action exists? (Not the current one.)

Something like Yii::$app->exist(controller/action);

Should it be possible check the route or something so?

What I need is to check if a parameter passed as

<?php echo Yii::$app->request->baseUrl.'/controller/action' ?>

to a JavaScript generic function exists before its execution via Ajax.

Upvotes: 3

Views: 2350

Answers (3)

Anatoly Rugalev
Anatoly Rugalev

Reputation: 1168

The most reliable way to do this is to create Action instance.

public function actionExists($controllerId, $actionId, $module = null)
{
    if ($module === null) {
        $module = Yii::$app;
    }
    $controller = $module->createControllerByID($controllerId);
    if ($controller === null) {
        return false;
    }
    $action = $controller->createAction($actionId);
    if ($action === null) {
        return false;
    }
    return true;
}

Upvotes: 3

allenfantasy
allenfantasy

Reputation: 41

Inspired by @vitalik_74, after referring the source code and testing I found this works in Yii 1.1:

function isActionExistsInController($actionId, $controllerId, $moduleId = null) {
  $route = $moduleId ? $moduleId.'/'.$controllerId.'/'.$actionId : $controllerId.'/'.$actionId;
  $controller = Yii::app()->createController($route);
  return !!$controller;
}

Upvotes: 0

vitalik_74
vitalik_74

Reputation: 4591

You may check this with use method_exists. Like that:

method_exists(Yii::$app->controllerNamespace . $controllerName, 'action' . ucfirst($actionName));// $actionName with first lette is uppercase

For more - http://php.net/manual/en/function.method-exists.php

EDIT:

Or you may use this way:

$controller = Yii::$app->createController('controller');// 
if (!$controller !== null && method_exists($controller, 'action')) {
   echo 'controller/action is allow :)';
}

Or I invented better way with use Yii2 Api:

$controller = Yii::$app->createController('controller');// 
if (!$controller !== null && $controller->hasMethod('action'))) {
   echo 'controller/action is allow :)';
}

Upvotes: 4

Related Questions