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.

General Questions /

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

Using currentUser() for field auto population


Reply


4 Posts   742 Views

Avatar
okotoker

Community Member, 41 Posts

9 September 2011 at 7:36am

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.

Avatar
simon_w

Forum Moderator, 474 Posts

9 September 2011 at 8:43am

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;
}

Avatar
okotoker

Community Member, 41 Posts

9 September 2011 at 9:09am

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?

Avatar
simon_w

Forum Moderator, 474 Posts

9 September 2011 at 9:15am

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