0

In our YII app, we would like to capture google analytics on validation failures. We are using modal rules for validating our data. Here is one of our validation modal code snippet

public function rules() {
    return [
          ['email', 'validateEmail'],
    ];
}

public function validateEmail($attribute_name, $params) {
    if (EMAIL EXITS IN DATABASE) {
        $this->addError($attribute_name, Yii::t('app', 'Email Already Exist.'));
        return false;
    }
}

It correctly shows an error message on our frontend but we can not track this in google analytics. We would like to call a javascript function whenever this validation fails. Here is our javascript function

function captureGAEvent(category, action, label) {
    alert(category + " " + action + " " + label);
    ga('send', 'event', category, action, label);
}

Please guide.

Alex
  • 1,406
  • 2
  • 18
  • 33

1 Answers1

0

yii2 documentation states that you could set up Client Side Validation

Which one has a clientValidateAttribute method Implementing Client Side Validation where you could put your analytics code as well.

You will need to enable enableClientValidation in your ActiveForm.

I would do following based on Deferred Validation paragraph.

Create a Validator Class

class UserEmailValidator extends Validator
{
    public function init()
    {
        parent::init();
        $this->message = 'Email Already Exist..';
    }

    public function validateAttribute($model, $attribute)
    {
        if (EMAIL EXISTS IN DATABASE) {
            $this->addError($attribute, Yii::t('app', $this->message));
            return false;
        }
    }

    public function clientValidateAttribute($model, $attribute, $view)
    {
        return <<<JS
        deferred.push($.get("/check-email-exists", {value: value}).done(function(data) {
            if ('' !== data) {
                messages.push(data);

                alert(category + " " + action + " " + label);
                ga('send', 'event', category, action, label);
            }
        }));
JS;
    }
}

Use it in your model

public function rules() {
    return [
          ['email', UserEmailValidator::class],
    ];
}
  • We don't prefer client-side validation. We want something which can be executed just after our serverside validation (through model call) executes successfully, – Alex Apr 13 '21 at 08:20
  • Hi @Alex, you could check this out: [Send event To google Analytics using server sided api](https://stackoverflow.com/questions/32200016/send-event-to-google-analytics-using-api-server-sided/32200270) there is a php libary for this: [theiconic/php-ga-measurement-protocol](https://github.com/theiconic/php-ga-measurement-protocol) and the yii2 libary which utilize it: [baibaratsky/yii2-ga-measurement-protocol](https://github.com/baibaratsky/yii2-ga-measurement-protocol). are you searching something like this? – Papp Péter Apr 14 '21 at 09:14