Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 How to call controller action from the view

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()
?>
like image 232
beginner Avatar asked Apr 28 '15 05:04

beginner


2 Answers

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.

like image 75
arogachev Avatar answered Sep 21 '22 12:09

arogachev


you can use this.

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

credits Metacrawler original question link

like image 31
Bloodhound Avatar answered Sep 18 '22 12:09

Bloodhound