In SilverStripe I want to return two fields when I use map
in a DropdownField
.
I have a data object Teacher
with fields firstname
and lastname
. So in my DropdownField
I want to merge these two fields and pass them to map()
.
My current code looks like this:
public function getCMSfields() {
$fields = FieldList::create(TabSet::create('Root'));
$fields->addFieldsToTab('Root.Main', array(
DropdownField::create('TeacherID', 'Teacher')->setSource(Teacher::get()->map('ID', 'Firstname'))->setEmptyString('Select one')
);
// etc...
return $fields;
}
How is it possible to merge firstname
and lastname
and pass it inside map()
and return it to the DropdownField
.
We can create get functions in our custom DataObject
to return any content that we like. These get functions can be used in lots of places, including the map
function.
Here is how to add a getFullName
function to return a FullName
string in our object:
class Teacher extends DataObject {
// ...
public function getFullName() {
return $this->FirstName . ' ' . $this->LastName;
}
}
Then in our DropdownField
we can fetch Teacher::get()->map('ID', 'FullName')
like so:
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldsToTab('Root.Main', array(
DropdownField::create('TeacherID', 'Teacher')
->setSource(Teacher::get()->map('ID', 'FullName'))
->setEmptyString('Select a teacher')
);
return $fields;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With