YII 2 NOTIFICATION PART 2 – MODIFY TO SEND TO DIFFERENT USERS, DELETE NOTIFICATIONS FOR ONE USER, SET ROUTE OF EACH NOTIFICATION

 


Source of Widget: https://github.com/webzop/yii2-notifications

Notify All Users
public function actionNotif4(){

$user = User::find()->all();

foreach ($user as $user){
 AccountNotification::create(AccountNotification::KEY_NEW_ACCOUNT, ['user' =>$user])->send($user);
 
 }return $this->render('index');
 }

Notify One specific user:
public function actionNotif(){

$user = User::findOne(2);

AccountNotification::create(AccountNotification::KEY_NEW_ACCOUNT, ['user' =>$user])->send($user);
 return $this->render('index');

}

Add to view by including in main.php
if (Yii::$app->user->identity->username != NULL){
 $menuItems[] = \webzop\notifications\widgets\Notifications::widget(); 
 }


Change routes at backends\notifications\AccountNotification.php
public function getRoute(){

switch($this->key){ 
case self::KEY_NEW_ACCOUNT: 
return ['/site/logout']; 
case self::KEY_RESET_PASSWORD: 
return ['/site/index']; 
} 
}
at vendor\webzop\yii2-notifications\controllers\DefaultController.php
public function actionDelete(){
 $userId = Yii::$app->getUser()->getId();

Yii::$app->getDb()->createCommand()->
 delete('notifications', 'user_id=:id', array(':id'=>$userId))->execute();

if(Yii::$app->getRequest()->getIsAjax()){
 return $this->ajaxResponse(1);
 }

Yii::$app->getSession()->setFlash('success', Yii::t('modules/notifications', 'All notifications have been deleted.'));

return Yii::$app->getResponse()->redirect(['/notifications/default/index']);

}
at vendor\webzop\yii2-notifications\views\default\index.php
 <a class="btn btn-danger" href="<?= Url::toRoute(['/notifications/default/delete']) ?>"><?= Yii::t('modules/notifications', 'Delete all'); ?></a>

vendor\webzop\yii2-notifications\Notification.php

public function send($user){
 $this->userId = $user->id;
 Yii::$app->getModule('notifications')->send($this);
 }


Post a Comment

0 Comments