Clone wiki

badger.yii / Events

Events and callback functions

For now there is only one event onSuccess. It will raise after badge successfuly given to user. By default there is no event but you can add event like this:

// Place it where you want to give user a badge
$Badge = new Badge;
$Badge->onSuccess = function($event){ // add custom event after giving badge to user
        // print_r( $event->params ); //some useful params
        echo 'Badge <b>'.$event->sender->name.'</b> given'; 

// Give badge to current user (no userID given as second param)
$Badge->checkAndGiveGroup( 'Login' ); //for all badges that defined as BADGE_LOGIN_*
// or just one badge
$Badge->checkAndGiveOne( Badge::BADGE_LOGIN_FIRST );

// Give badge to another user
// ! note second param is User ID
$Badge->checkAndGiveOne( Badge::BADGE_LOGIN_FIRST, $offlineUserId = 102 );


Check all and give badges automaticaly

If you have created parent of all your models MyAciveRecord (in protected/components/) you can edit it as:


      // callback function afer giving badge to user
      public function notifyUser($event) {
            $Badge = $event->sender; // Now you can access $Badge->name
            Yii::app()->user()->setFlash('info','You have earned the badge');

      public function afterSave() {

            if ($this->isNewRecord) {

                  $Badge = new Badge;
                  $Badge->onSuccess = array( $this, 'notifyUser');
                  $badgeIdArr = $Badge->checkAndGiveGroup( get_class($this) );


            return parent::aferSave();


I'm using this method to automaticaly check badges for all my models (that are extended from MyActiveRecord).

Comment extends MyActiveRecord
Page extends MyActiveRecord
Message extends MyActiveRecord

.. So after saving new Comment code will check available badges It will come like this: $Badge->checkAndGiveGroup('Comment');

And for Page and Message the same:

  • $Badge->checkAndGiveGroup('Page');
  • $Badge->checkAndGiveGroup('Message');

because we are using get_class($this) which detects active model we are using.

And if there is no such badge it will stop checking early (because there is no such constant and it will not check database)