Huy Tran
Huy Tran

Reputation: 4431

Call function in another controller from a controller in Yii

I want to call a function in another controller from the controller.

class FirstController extends Controller {
      public function test1() { return 'OK'; }
}
class SecondController extends Controller {
      public function callTest1() { First::test1(); }
}

--> server error
Help me resolve it.

Upvotes: 5

Views: 25278

Answers (8)

Senthil
Senthil

Reputation: 634

Instead of using createController which creates an instance based on a route, when calling via code, it's probably best to use createControllerByID.

    $first = Yii::$app->createControllerByID('first');
    $first->test1();

Make sure test1 is public function

Upvotes: 1

danish ali
danish ali

Reputation: 132

This worked for me,

for PatientsController and method printPublicReport() with $params = $patientId, $appId, $testIds

    list($patient) = Yii::$app->createController('patients/print-public-report', $postDataAry); 

    $patient->printPublicReport($patientId, $appId, $testIds);

Upvotes: 0

Mohan raj
Mohan raj

Reputation: 11

In Yii2 basic application following component will be use to call action

Yii::$app->runAction('controllername/create', $params);

Upvotes: 1

Bea
Bea

Reputation: 21

You can also use Yii::$app->runAction().

Upvotes: 1

Denis Volkov
Denis Volkov

Reputation: 59

The word 'Controller' should not be used when calling createController() and you should take [0] element of the result, before calling functions

 $process = Yii::app()->createController('First'); //create instance of FirstController
 $process=$process[0];
 $process->test1(); //call function 

Upvotes: 1

Maug Lee
Maug Lee

Reputation: 915

If method test1 in your FirstController is not using $this you can simply make it static. Instead of:

public function test1() { return 'OK'; }

sign it as:

public static function test1() { return 'OK'; }

Then you can call it from everywhere:

FirstController::test1();

It all depends on your needs...

Upvotes: 0

pragnesh patel
pragnesh patel

Reputation: 1

You cannot call directly your function: first create instance of controller, then call function:

$process = Yii::app()->createController('FirstController'); //create instance of controller

$process->test1(); //call function 

Upvotes: 0

Jon
Jon

Reputation: 437336

You cannot call that method directly because it's not static, so you 'd have to create an instance of FirstController first. When you want to do that, use CWebApplication::createController:

// supply appropriate route in place of 'first/index'
list($first) = Yii::app()->createController('first/index');
$first->test1();

However, there shouldn't be a need to call methods from another controller; this is a bad code smell. Perhaps it would be more appropriate to refactor your code and pull it out of the controller (maybe into a model).

Upvotes: 9

Related Questions