This should be relatively simple. I know how to create a form and hide it and show it if a specific option
is selected
I want to have a Dropdown
populated with a specific DataObject
. That much is simple. But I need to add an option that says 'Add new' to this Dropdown
, which is in a form
I can handle the submission (like if the value is something like 'new' instead of an ID
), but I do not know how to add this option into the select
with Silverstripe
, or if it is even possible. Any help is appreciated!
You can use a DropdownField and populate it with whatever key value pairs you want. For example:
$itemsField = DropdownField::create(
'Items',
'Items',
['add-new' => 'Add new'] + $this->Items()->map()->toArray()
);
The third argument is an array that gets turned into the option
html elements for the drop down.
Then you can add it to your form's FieldList
:
$form = Form::create(
$this,
'MyForm',
FieldList::create(
[
$someField,
$someOtherField,
$itemsField
]
),
$actions,
$requiredFields
);
A Dropdown for selecting a $has_one
is fine. E.g. if you have a list of Addresses
and want to select the Country
.
Sometimes a new Country
has to be added. For this i used the quickaddnew extension which adds a nice button "add new" beneath the dropdown and opens a form in a modal for adding the new item. You can use it in your code like this:
public function getCMSFields() {
/**
* @FieldList
*/
$fields = parent::getCMSFields();
$countries = function() {
return Country::get()->map('ID','Title')->toArray();
};
$country = new DropdownField('CountryID', 'Country', $countries());
$country->setEmptyString('-- please select --');
$country->useAddNew('Country', $countries);
$fields->insertAfter($country, 'Telephone');
$fields->removeByName('SortOrder');
return $fields;