Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

How to update page witout versioning or how to add view counter?


Go to End


2 Posts   1889 Views

Avatar
jjeziorski

Community Member, 11 Posts

6 July 2009 at 12:38am

Hey all,

I would like to track number of views of each page, so i wrote:

class Page extends SiteTree {
	public static $db = array(
	    'Viewed' => 'Int'
	);
}
class Page_Controller extends ContentController {
	
public function init() {
parent::init();
      if ($this->ID) {
    	if (!Session::get('Visited_'.$this->ID)) {
        $page = DataObject::get_by_id('Page', $this->ID);
        
        if ($page) {
          $page->Viewed++;
          $page->writeToStage("Stage");
          $page->publish("Stage", "Live");
        }
      Session::set('Visited_'.$this->ID, true);
      }
    }
}

This solution works however i end up with huge amount of version copies (each for one view increment)

Is there any way to avoid versioning on save? Or is there a better solution?

Thanks,

Avatar
jjeziorski

Community Member, 11 Posts

6 July 2009 at 6:19pm

I've got this (i used solution from forum module) :)

$this->Viewed++;
$SQL_numViews = Convert::raw2sql($this->Viewed);
DB::query("UPDATE Page_live SET Viewed = '$SQL_numViews' WHERE ID = $this->ID");

Well, i don't mind using sql, however this approach is database specific and might be broken. It might be a good idea to have function like unversionedWrite or write() with boolean param.

Or am i missing something? Any other ideas?

Thanks