How to call a module from a view

Folks, I promise I’ve searched everywhere for an answer and I can’t find one.

Here’s the vibe:

I have created a module. It’s an incredibly simple module. It has a method (perhaps you prefer the word ‘Action’) called hello(). When called, hello just echoes the words “hello world” to the screen, using echo “hello world”;

Is there a way that I can call this module - and specifically the hello() action - from a file in my main views folder?

This will be on a module for eventually posting comments on a webpage.

On Codeigniter this would be easily achieved by going into the view file and saying:

echo Modules::run(‘moduleName/hello’); //calls a module and gets the module to say ‘hello world’

Is there a way to do the same thing with Yii2?

Thanks!

Well, the Module in Yii is not like that in CodeIgniter.

What you want to do will be achieved more easily and better with Widget in Yii.




<?php echo app\components\MyWidget::widget(['message' => 'Hello!']); ?>



http://www.yiiframework.com/doc-2.0/guide-structure-widgets.html

Well, thank you for that. I’m very grateful.

Can I just ask a quick follow up question?

What if you want your widget to do some kind of database query? Let say, for example, you want to add a comments section to the bottom of a page (very common). This widget would require two features:

  • a means of querying the db and looping through the results - displaying all of the comments on the page.

  • a textarea at the top of the page which allows users to submit a new comment

I’m not asking you to write the code for me but I would be very grateful if you could just outline the general concepts/stategies for making that happen.

Many thanks.

my advice, create the hello() functon as a method of module, and you can call it everywhere with :


Yii::$app->getModule('modulename')->hello();

Hello Sheillendra,

Thanks for that. I’m excited to discover that what I’m trying to achieve may be possible. Unfortunately, there’s a fly in the ointment. I’m getting a syntax error.

[b]Unknown Method – yii\base\UnknownMethodException

Calling unknown method: app\modules\comments\Comments::hello()[/b]

Perhaps it has something to do with my hello() method residing in the ‘DefaultController.php’ file.

I’d be very grateful if you could offer some advice.