Save Optionset value checked
August 18, 2025 · AI Conversations
$Title
we have created custom option field in silver stripe how to show selected
Here’s your snippet adjusted:
<div class="radio_group">
<label class="form-label">$Title</label>
<div class="d-flex">
<% loop $Options %>
<label class="radio-wrapper" for="$ID">
<input
type="radio"
name="$Name"
id="$ID"
value="$Value.ATT"
$AttributesHTML
<% if $isChecked %>checked="checked"<% end_if %>
/>
<span class="custom-radio"></span> $Title.XML
</label>
<% end_loop %>
</div>
</div>
Pre-selecting from PHP (optional):
$field = OptionsetField::create('MyField', 'Choose one', [
'a' => 'Option A',
'b' => 'Option B',
]);
// Set previously saved value, or default
$field->setValue($record->MyField ?? 'b');
If you’re editing an existing record and building the form with `$form->loadDataFrom($record)`, the correct option will be marked via `$isChecked` automatically.
$fields = FieldList::create([
HiddenField::create('WorkerID', 'WorkerID')->setValue($id),
OptionsetField::create('Anrede', 'Anrede*', [
'Herr' => 'Herr',
'Frau1' => 'Frau',
'Ansonsten' => 'Ansonsten',
]
)->addExtraClass('radio_group'),
extract like this to show checked in template
'Anrede' => $form->Fields()->dataFieldByName('Anrede'),
but save value not showing as checked
1) **Option keys vs. saved value don’t match**
Optionset stores the **array key** as the value. You have `'Frau1' => 'Frau'`. If the DB has `Frau`, nothing will be checked.
Fix either the keys or the stored value.
OptionsetField::create('Anrede', 'Anrede*', [
'Herr' => 'Herr',
'Frau' => 'Frau', // <- make key match what you save
'Ansonsten' => 'Ansonsten',
]);
2) **Form not preloaded with the record**
You must load the saved data **before** you pass the field to the template.
$form = Form::create($this, 'MyForm', $fields, $actions, $validator);
// assuming $record has Anrede column
if ($record) {
$form->loadDataFrom($record);
// or: $fields->dataFieldByName('Anrede')->setValue($record->Anrede);
}
// Then pass the field object to the template
$data = [
'Anrede' => $form->Fields()->dataFieldByName('Anrede'),
];
return $this->customise($data)->renderWith([...]);
3) **Template markup**
If you’re custom-rendering, loop the options and use `$isChecked`:
<% with $Anrede %>
<div class="radio_group">
<label class="form-label">$Title</label>
<div class="d-flex">
<% loop $Options %>
<label class="radio-wrapper" for="$ID">
<input type="radio"
name="$Name"
id="$ID"
value="$Value.ATT"
$AttributesHTML
<% if $isChecked %>checked="checked"<% end_if %> />
<span class="custom-radio"></span> $Title.XML
</label>
<% end_loop %>
</div>
</div>
<% end_with %>
Quick debug checks:
– `Debug::dump($form->Fields()->dataFieldByName('Anrede')->Value());` → should print the saved value (e.g., `Frau`).
– If it prints `Frau` but nothing is checked, your options’ **keys** must include `Frau`.
If you must keep the `Frau1` key for some reason, map it before loading:
$val = $record->Anrede === 'Frau' ? 'Frau1' : $record->Anrede;
$fields->dataFieldByName('Anrede')->setValue($val);
Do these two things (matching keys + `loadDataFrom`) and the checked state will show correctly.
OptionsetField::create('Anrede', 'Anrede*', [
'Herr' => 'Herr',
'Frau' => 'Frau', // 'Ansonsten',
]);
### 1) Make sure the field has a value before you pass it to the template
Load the record onto the **form** (or set the field value manually) **before** you extract the field:
$fields = FieldList::create([
HiddenField::create('WorkerID')->setValue($id),
OptionsetField::create('Anrede', 'Anrede*', [
'Herr' => 'Herr',
'Frau' => 'Frau',
'Ansonsten' => 'Ansonsten',
])->addExtraClass('radio_group'),
]);
$form = Form::create($this, 'MyForm', $fields, FieldList::create());
// Critical: preload saved value
if ($record) {
$form->loadDataFrom($record); // ensures Anrede gets its saved value
// or: $fields->dataFieldByName('Anrede')->setValue($record->Anrede);
}
// Now extract for the template (after value is set)
return $this->customise([
'Anrede' => $form->Fields()->dataFieldByName('Anrede'),
])->renderWith([...]);
### 2) In your template, use `$AttributesHTML` (not `$Attributes`) and/or `$isChecked`
`$AttributesHTML` includes “checked” when appropriate. If you’re custom-marking up, do this:
<% with $Anrede %>
<div class="radio_group">
<label class="form-label">$Title</label>
<div class="d-flex">
<% loop $Options %>
<label class="radio-wrapper" for="$ID">
<input
type="radio"
name="$Name"
id="$ID"
value="$Value.ATT"
$AttributesHTML
<% if $isChecked %>checked="checked"<% end_if %>
/>
<span class="custom-radio"></span> $Title.XML
</label>
<% end_loop %>
</div>
</div>
<% end_with %>
### Quick sanity check
Drop this temporarily where you build the view:
// Should output e.g. "Frau"
SilverStripeDevDebug::dump($form->Fields()->dataFieldByName('Anrede')->Value());
If that prints the saved key (e.g. `Frau`) but nothing is checked, the fix is almost always switching to `$AttributesHTML` and/or ensuring you loaded the record **before** extracting the field.
### Drop-in replacements
**AddWorkerForm** (now accepts `$record = null` and preloads value)
public function AddWorkerForm($record = null)
{
// If a record is passed (edit), prefer that ID; else fall back to route param
$routeID = (int)$this->getRequest()->param('ID');
$workerID = $record && $record->ID ? (int)$record->ID : $routeID;
$fields = FieldList::create([
HiddenField::create('WorkerID', 'WorkerID')->setValue($workerID),
OptionsetField::create('Anrede', 'Anrede*', [
'Herr' => 'Herr',
'Frau' => 'Frau',
'Ansonsten' => 'Ansonsten',
])->addExtraClass('radio_group'),
TextField::create('Titel', 'Titel')->setAttribute('placeholder', 'Titel*'),
TextField::create('FirstName', 'Vorname')->setAttribute('placeholder', 'Vorname*'),
TextField::create('LastName', 'Nachname')->setAttribute('placeholder', 'Nachname'),
DropdownField::create('CountryCode', 'Country Code', [
'+49' => 'Deutschland (+49)',
'+43' => 'Österreich (+43)',
'+41' => 'Schweiz (+41)'
])->setEmptyString('Ländervorwahl auswählen*'),
TextField::create('Telefon', 'Telefon')->setAttribute('placeholder', 'Telefon*'),
EmailField::create('Email', 'Emailadresse')->setAttribute('placeholder', 'Emailadresse*'),
EmailField::create('ZusaEmail', 'Zusatizliche mailadresse')->setAttribute('placeholder', 'Zusatizliche mailadresse'),
TextField::create('PositionUnterneehmen', 'Position Unterneehmen')->setAttribute('placeholder', 'Position Unterneehmen'),
TextField::create('Mobile', 'Mobiel')->setAttribute('placeholder', 'Mobiel'),
TextField::create('Fax', 'Fax')->setAttribute('placeholder', 'Fax'),
OptionsetField::create('StandaardContact', '', [
'1' => 'Standaard Contact'
])->addExtraClass('radio_group'),
]);
$actions = FieldList::create([
FormAction::create('doSaveWorker', 'Speichern')->addExtraClass('btn btn-primary')
]);
$validator = RequiredFields::create(['Anrede', 'Titel', 'FirstName', 'LastName', 'CountryCode', 'Telefon', 'Email']);
$form = Form::create($this, 'AddWorkerForm', $fields, $actions, $validator);
$form->setFormAction('/public/dashboard/doSaveWorker');
// ✅ Preload values (edit) or any session/post back (create)
if ($record) {
$form->loadDataFrom($record);
} elseif ($sessionData = $this->getRequest()->getSession()->get('WorkerData')) {
$form->loadDataFrom($sessionData);
}
return $form;
}
**Editworker** (pass the record into `AddWorkerForm`)
public function Editworker(HTTPRequest $request)
{
$id = (int)$request->param('ID');
$worker = RentalWorkerInformation::get()->byID($id);
if (!$worker) {
return $this->httpError(404, 'Worker not found');
}
// ✅ Build form with record so values (incl. Anrede) are set
$form = $this->AddWorkerForm($worker);
return $this->customise([
'Title' => 'Miet arbeiter bearbeiten',
'Form' => $form,
'WorkerID' => $form->Fields()->dataFieldByName('WorkerID'),
'Anrede' => $form->Fields()->dataFieldByName('Anrede'),
'Titel' => $form->Fields()->dataFieldByName('Titel'),
'Vorname' => $form->Fields()->dataFieldByName('FirstName'),
'Nachname' => $form->Fields()->dataFieldByName('LastName'),
'CountryCode' => $form->Fields()->dataFieldByName('CountryCode'),
'Telefon' => $form->Fields()->dataFieldByName('Telefon'),
'Email' => $form->Fields()->dataFieldByName('Email'),
'ZusaEmail' => $form->Fields()->dataFieldByName('ZusaEmail'),
'PositionUnterneehmen' => $form->Fields()->dataFieldByName('PositionUnterneehmen'),
'Mobile' => $form->Fields()->dataFieldByName('Mobile'),
'Fax' => $form->Fields()->dataFieldByName('Fax'),
'StandaardContact' => $form->Fields()->dataFieldByName('StandaardContact')
])->renderWith(['Layout/Broker/Addworker', 'Page']);
}
### Template reminder (for radios)
When you render `Anrede` manually, loop options and either print `$AttributesHTML` **or** check `$isChecked`:
<% with $Anrede %>
<div class="radio_group">
<label class="form-label">$Title</label>
<div class="d-flex">
<% loop $Options %>
<label class="radio-wrapper" for="$ID">
<input type="radio"
name="$Name"
id="$ID"
value="$Value.ATT"
$AttributesHTML
<% if $isChecked %>checked="checked"<% end_if %> />
<span class="custom-radio"></span> $Title.XML
</label>
<% end_loop %>
</div>
</div>
<% end_with %>
With these changes, the saved `Anrede` will show as checked when editing, and any prefilled/new-session values will also reflect correctly on create.