Jump to:

22997 Posts in 11853 Topics by 2828 members

General Questions

SilverStripe Forums » General Questions » How to update page witout versioning or how to add view counter?

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

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

Page: 1
Go to End
Author Topic: 993 Views
  • jjeziorski
    Avatar
    Community Member
    11 Posts

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

    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,

  • jjeziorski
    Avatar
    Community Member
    11 Posts

    Re: How to update page witout versioning or how to add view counter? Link to this post

    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

    993 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.