Jump to:

23478 Posts in 18950 Topics by 2878 members

General Questions

SilverStripe Forums » General Questions » Using currentUser() for field auto population

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: 712 Views
  • okotoker
    Avatar
    Community Member
    41 Posts

    Using currentUser() for field auto population Link to this post

    I am trying to do something that seems fairly simple, but has hitched me up. I am trying to auto populate the "author" field with the current user name. I am using:

    class NewsPage extends Page {
    static $db = array(
    'Date' => 'Date',
        'Author' => 'Varchar'
    );
    static $has_one = array();      
          function getCMSFields() {
             $member = Member::currentUser();
             
             $f = parent::getCMSFields();
             $f->addFieldToTab("Root.Content.Main", new TextField("Author", "Author", $member->FirstName));
             
             return $f;
          }   
       }

    I am not seeing anything show up in the field. I have also tried just dropping in a "test" into the value field with no luck.

  • simon_w
    Avatar
    Forum Moderator
    473 Posts

    Re: Using currentUser() for field auto population Link to this post

    This is because the CMS loads all field values from the class before returning the form, but after your defaults have been applied.

    If you just want to set the Author value on creation, you can use the populateDefaults() function, using something like:

    public function populateDefaults() {
    parent::populateDefaults();
    $this->Author = Member::CurrentUser()->FirstName;
    }

  • okotoker
    Avatar
    Community Member
    41 Posts

    Re: Using currentUser() for field auto population Link to this post

    Thanks, that will do the trick, even easier than I thought. So what is the purpose of adding the "value" parameter when setting up the field?

  • simon_w
    Avatar
    Forum Moderator
    473 Posts

    Re: Using currentUser() for field auto population Link to this post

    That's mainly used for frontend forms, to provide a default value.

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