/** * Enable / Disable multiple Google Analytics Accounts * * @param $status * @return \yii\web\Response * @throws NotFoundHttpException * @throws \Exception */ public function actionUpdateStatus($status) { $accounts = Account::findAll(['id' => Yii::$app->getRequest()->post('ids')]); if (empty($accounts)) { throw new NotFoundHttpException(Yii::t('google_analytics', 'Page not found.')); } else { foreach ($accounts as $account) { $account->status = $status; $account->update(); } Yii::$app->getSession()->setFlash('success', Yii::t('google_analytics', 'The selected items have been successfully updated.')); return $this->redirect(['index']); } }
/** * Event Handler * After a view is rendered * * @param $event */ public function addTrackingCode($event) { if (isset($event, $event->sender, $event->sender->context, $event->sender->context->actionParams) && isset($event->sender->context->module, $event->sender->context->module->requestedRoute) && $event->sender->context->module->requestedRoute === "app/embed") { // Add tracking code only to app/embed view $formID = isset($event->sender->context->actionParams['id']) ? (int) $event->sender->context->actionParams['id'] : null; $accounts = Account::findAll(['form_id' => $formID, 'status' => 1]); if (count($accounts) > 0) { $gaCode = <<<EOT <!-- Google Analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); EOT; foreach ($accounts as $account) { $gaCode .= <<<EOT ga('create', '{$account->tracking_id}', 'auto', { 'name': 'tracker{$account->id}', 'cookieDomain': '{$account->tracking_domain}', 'legacyCookieDomain': '{$account->tracking_domain}' }); EOT; if ($account->anonymize_ip) { $gaCode .= <<<EOT ga('tracker{$account->id}.set', 'anonymizeIp', true); EOT; } $gaCode .= <<<EOT jQuery(document).ready(function(){ \$(options.name).on('fill', function(event){ // Track fill ga('tracker{$account->id}.send', 'event', 'Form #{$account->form_id}', 'Fill', 'Start', null); }); \$(options.name).on('error', function(event){ // Track submits with validation error ga('tracker{$account->id}.send', 'event', 'Form #{$account->form_id}', 'Submit', 'Error', null); }); \$(options.name).on('success', function(event){ // Track submits with success ga('tracker{$account->id}.send', 'event', 'Form #{$account->form_id}', 'Submit', 'Success', null); }); }); EOT; } $gaCode .= <<<EOT </script> <!-- End Google Analytics --> </body> EOT; $content = $event->output; $event->output = str_replace("</body>", $gaCode, $content); } } }