Jump to:

17452 Posts in 4473 Topics by 1971 members

Archive

SilverStripe Forums » Archive » How to reference Model methods from Controler?

Our old forums are still available as a read-only archive.

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

Page: 1
Go to End
Author Topic: 1804 Views
  • TomDude48
    Avatar
    Community Member
    2 Posts

    How to reference Model methods from Controler? Link to this post

    I have found myself duplicating methods in a Model and its related Controler.
    E.g.

    Blog extends Page() {
       function Posts($numPerPage) {
          return DataObject::get("Post","BlogID=$this->ID","","",(int)$_GET['start'] . ", $numPerPage"");
       }
    }

    Blog_Controller extends Page_Controller() {
       function Posts() {
          return DataObject::get("Post","BlogID=$this->ID","","",(int)$_GET['start'] . ", 8");
       }
    }

    I was looking for a way to just use the function in the Model class and noticed that model class functions are inherited automatically,

    E.g. just remove the Post function from the controler and the $this->Post() will call the function in the Model. However, parent does not seem to work like it does with other functions such as init().

    E.g. the below call to parent::Posts() does not work, but parent::init() does work.

    Blog_Controller extends Page_Controller() {
       function init() {
          parent::init();   
       }
       
       function Posts($id) {
          parent::Posts(8);
       }
    }

    Any ideas on how to refernce the model function when you have a function with the same name in the controller?

  • Sean
    Avatar
    Forum Moderator
    921 Posts

    Re: How to reference Model methods from Controler? Link to this post

    Good question, I do know that if you have a method on the controller, and if you reference a DB field, or relation by calling $this->Field() (replace Field with your DB field name) then it works. However, I'm not sure if you can call a method on the model the same way (not a DB field).

    Does this example work, perhaps?

    class Page extends SiteTree {

    function Posts() {
    return 'Lots of posts!';
    }

    }

    class Page_Controller extends ContentController {

    function Posts() {
    return $this->Posts();
    }

    }

    Cheers,
    Sean

  • Fuzz10
    Avatar
    Community Member
    787 Posts

    Re: How to reference Model methods from Controler? Link to this post

    <subscribe to thread>

    1804 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.