Yii2 How to call controller action from the view

beginner picture beginner · Apr 28, 2015 · Viewed 17.4k times · Source

I have a function in the controller that manipulates data the way I wanted. Now I want to call that function in the index.php file in the view. How do I do that?

In my controller

function actionTesting($params){
    .....
}

How can I call it in the view like..

<?php
   echo $this->testing($params);//Calling unknown method: yii\web\View::testing()
?>

Answer

arogachev picture arogachev · Apr 28, 2015

You should not call controller actions from view. I think it violates MVC pattern.

As for the error, it's clear, $this in view refers to yii\web\View, not to the controller and testing method obviously doesn't exist there.

There is similar question asked before, here is possible solution (credits for Manesh):

Yii::$app->runAction('controller/action', ['param1' => 'value1', 'param2' => 'value2']);

This is not enough to just call controller action as usual method call because some events need to be applied, etc.

I don't recommend to use this approach, it's better to move your logic to component / model depending on type of it.