How to set the default value for a form select element?
I have the following code but is not working.
$this->add([
'name' => 'country',
'type' => Form\Element\Select::class,
'options' => [
'label' => 'Country',
'empty_option' => '',
'value_options' => $this->prepareCountries(), // this returns an array of countries
'unselected_value' => null,
'use_hidden_element' => true,
],
'attributes' => [
'value' => '28',
'required' => 'required',
'class' => 'form-control',
],
]);
Hi @Francisc_Tar,
You’ve done everything right in terms of setting the default value here.
The only thing left is to check your array values returning from $this->prepareCountries(). Thanks!
Hi @ALTAMASH80
Thanks for your answer,
The function does return values. I have the options and I can select them but the default value is not working.
$this->add([
'name' => 'address_country',
'type' => Form\Element\Select::class,
'options' => [
'label' => 'some label',
'empty_option' => '',
'value_options' => [
1 => 'aa',
2 => 'bb',
3 => 'cc',
4 => 'dd',
5 => 'ee',
],
'unselected_value' => null,
'use_hidden_element' => true,
],
'attributes' => [
'value' => 4,
'required' => 'required',
'class' => 'form-control',
],
]);
Still does not select the default value.
Sir @Francisc_Tar, I can assure you it works. This is the output which I get in Laminas form.
<label><span>some label</span><input type="hidden" name="address_country" value="">
<select name="address_country" required="required" class="form-control">
<option value=""></option>
<option value="1">aa</option>
<option value="2">bb</option>
<option value="3">cc</option>
<option value="4" selected="selected">dd</option>
<option value="5">ee</option></select></label>
Thanks!
Okay, I found the issue. Oh, silly me! Wrong entity binding. Thanks @ALTAMASH80
I’m glad that I can be of help to you @Francisc_Tar.