Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set two fields using map

Tags:

silverstripe

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.

like image 904
Ivan Avatar asked Jun 18 '16 13:06

Ivan


1 Answers

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;
}
like image 85
3dgoo Avatar answered Sep 22 '22 05:09

3dgoo