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

Using currentUser() for field auto population


Go to End


4 Posts   1160 Views

Avatar
okotoker

Community Member, 50 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
(deleted)

Community Member, 473 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, 50 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
(deleted)

Community Member, 473 Posts

9 September 2011 at 9:15am

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