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.

Data Model Questions /

[SOLVED] How to create non-static default values or preselect DropDownFields?


Reply


5 Posts   1913 Views

Avatar
bkausbk

Community Member, 11 Posts

26 January 2010 at 12:29am

Edited: 09/02/2010 9:54pm

Is there a way to create non static default values. Usually all default values are defined in $default array like:

static $defaults = array(
   'Live' => true
);

I want to assign the ID of the member who created a news article page. For this purpose I created a relation like:

public static $has_one = array(
   'Author' => 'Member'
);

This will create a new AuthorID in my NewsArticle related database table.
Each time a registered user creates a new NewsArticle, a DropDownField on CMS page should be displayed with preselected own Member (Member::currentUserID()) name. The user/news administrator should be able to change the member who created the specified news article.

The problem is, how can I pre select that member in the created DropDownList? What I tried so far is following:

[...]
$members = DataObject::get('Member');
if ($members) {
   $membersmap = $members->map_multiple("ID", array("FirstName", "Surname"));
} else {
   $membersmap = null;
}
$authorfield = new DropdownField('AuthorID', 'Author', $membersmap, Member::currentUserID());
$fields->addFieldToTab('Root.Content.Main', $authorfield, 'Content');

As I found out, the 4th argument in DropDownField ctor is the default value. But if a new news article page is created this 4th argument will be ignored, is always reset to 0. What can I do here to pre select a specified entry in DropDownField?

Even $authorfield->value = Member::currentUserID() didn't work. Is there maybe a bug in SilverStripe?
I'm using SilverStripe 2.3.4.

Thank's for help,
bkausbk

Attached Files
Avatar
bkausbk

Community Member, 11 Posts

2 February 2010 at 12:18am

Does anybody has an idea here? Or how would you solve my problem in another way?

Avatar
CodeGuerrilla

Community Member, 105 Posts

2 February 2010 at 4:40pm

Edited: 02/02/2010 4:41pm

* deleted *

Avatar
ajshort

Community Member, 244 Posts

2 February 2010 at 4:44pm

The way to do this is to overload populateDefaults() in your SiteTree sub-class - this is called when a new object is created. Just make sure to call the parent method as well. Something like this should do the job:

public function populateDefaults() {
   $this->AuthorID = Member::currentUserID();
   parent::populateDefaults();
}

Avatar
bkausbk

Community Member, 11 Posts

2 February 2010 at 11:47pm

Thank you ajshort, this was exactly what I was looking for.

But what is the 4th argument in DropDownField for? As far as I found out by viewing the source is that the 4th argument is the default value for that DropDownField.