6

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()
?>
rob006
  • 21,383
  • 5
  • 53
  • 74
beginner
  • 2,024
  • 5
  • 43
  • 76

3 Answers3

12

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.

Community
  • 1
  • 1
arogachev
  • 33,150
  • 7
  • 114
  • 117
1

you can use this.

echo $this->context->testing($params); 

credits Metacrawler original question link

Bloodhound
  • 2,906
  • 11
  • 37
  • 71
0

you can do like this

 $parse = array(
   ...............
   'aliasName' => $this,
   ..............
);
return $this->render('viewFile',$parse);

and than you can call the function like

<?php echo $aliasName->testing($param) ?>