registerJS in custom Component

Hi everyone, I’m new to this community :sweat_smile:
I’m making my own component. This is meant to show notifications to user based on some alerts checked on init.

namespace app\components;

use Yii;
use yii\base\Component;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use app\models\User;

class MyNotification extends Component
{
public $notes = array();

public function init()
{
    if (!Yii::$app->user->isGuest)
    {
        $user = User::findIdentity(Yii::$app->user->id);
        if (sha1($user->username) == $user->password)
        {
            $value = [
                'alertLevel' => 2,
                'type' => 'warning',
                'title' => Yii::t('app','Weak password'),
                'message' => Yii::t('app','Please change your password'),
                'url' => Url::to('/user/change-password')
            ];
            ArrayHelper::setValue($this->notes, 'weakPassword', $value);
        }
        if ($user->verified == false)
        {
            $value = [
                'alertLevel' => 1,
                'type' => 'error',
                'title' => Yii::t('app','Unverified account'),
                'message' => Yii::t('app','Check your email to verify your account'),
                'url' => Url::to('/user/resend-confirm')
            ];
            ArrayHelper::setValue($this->notes, 'unverifiedAccount', $value);
        }
    }
}
public function count()
{
    return count($this->notes);
}
public function render_notification_list()
{
    $_list = '';
    foreach ($this->notes as $note)
    {
        $_list .= '<li>'
                . '<a href="'.$note['url'].'" class="clearfix">'
                .'<span class="title">'.$note["title"].'</span>'
                .'<span class="message">'.$note["message"].'</span>'
                .'</a></li>';
    }
    return $_list;        
}
public function showAlerts()
{
    if ($this->count() > 0)
    {
        $js = '';
        foreach ($note->notes as $item)
        {
            $js .= 'var notice = new PNotify({'
            . ' title: "'.$item['title'].'",'
            . ' text: "'.$item['message'].'",'
            . ' type: "'.$item['type'].'",'
            . ' addclass: "click2close",'
            . ' hide: false,'
            . ' buttons: {'
            . '  sticker: false'
            . ' }'
            . '});';
        }
        // now registerJS
    }
}

}

In the “showAlerts()” function I would like to registerJS in order to make the PNotify alert appear. Is it possible to make it inside a Component?

Ok… me dumbass. It was simpler than I believed :sweat:

        Yii::$app->getView()->registerJs($js, \yii\web\View::POS_READY);

Sorry for the stupid question :sweat_smile:

1 Like