All Tutorials

Your One-Stop Destination for Learning and Growth

Getting Started with Yii2: Part 4 - Widgets

In our previous posts, we covered the basics of Yii2 application development, exploring models, views, and controllers. In this part, we'll delve into the power of Yii2 widgets.

What are Widgets?

Widgets are reusable UI components that can be embedded in any view. They offer a convenient way to encapsulate complex functionality and reduce code duplication. In essence, they represent self-contained functions that perform specific tasks, such as displaying calendars, menus, or search forms.

Creating a Custom Widget

Let's build a simple custom widget called HelloWidget. This widget will display a custom message when invoked in a view.

  1. First, create a new file named HelloWidget.php under the protected/widgets directory with the following content:
namespace app\widgets;

use yii\BaseComponent;

class HelloWidget extends BaseComponent
{
    public $message = 'Welcome to Yii2!';

    public function run()
    {
        return $this->render('hello', ['message' => $this->message]);
    }
}

Here, we define the HelloWidget class extending Yii's BaseComponent. We also set a default message and override the run() method to render our view.

  1. Next, create a new file named hello.php under the protected/views/widgets directory with the following content:
<?php
use Yii;
use yii\helpers\Html;
use app\widgets\HelloWidget as Hello;

/* @var $this \yii\web\View */
/* @var $model \app\models\LoginForm */

$message = Yii::$app->has('helloWidget') ? Yii::$app->get('helloWidget')->message : 'Welcome to Yii2!';
?>
<div>
    <?= Html::encode($message) ?>
</div>

In this file, we set up the required imports and initialize our HelloWidget. We also render the custom message using the widget's message property.

  1. Now, let's use our new widget in a view. Open or create a file named index.php under the protected/views/site directory with the following content:
<?php
use yii\helpers\Html;
use app\widgets\HelloWidget as Hello;

/* @var $this \yii\web\View */

$this->title = 'About';
$hello = new Hello();
?>
<div class="site-about">
    <h1><?= Html::encode($this->title) ?></h1>

    <?= $hello->render() ?>
</div>

Here, we import our HelloWidget, initialize a new instance, and include it in the view by calling its render() method.

  1. Finally, let's use this new widget in our application by visiting the /site/about URL.

Conclusion

In this part of our series on getting started with Yii2 application development, we covered how to create and use custom widgets. Widgets are an essential feature that can help you build complex applications more efficiently. They provide a convenient way to encapsulate functionality, reducing code duplication and making your application more maintainable.

In our next post, we'll explore the advanced features of Yii2, including caching, events, and dependency injection. Stay tuned!

Published July, 2017