Set two fields using map
Asked Answered
J

1

5

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.

Jasminjasmina answered 18/6, 2016 at 13:15 Comment(0)
F
10

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;
}
Foregut answered 19/6, 2016 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.