Reputation:
I had a user submit a form, and some of the fields were dropdowns like so
<div class="form-group row">
<label for="type" class="col-md-3 col-form-label text-md-right">Type</label>
<div class="col-md-9">
<select class ="form-control" id="type" name="type">
<option>Apartment</option>
<option>House</option>
<option>Studio</option>
<option>Flat</option>
</select>
@if ($errors->has('type'))
<span class="invalid-feedback">
<strong>{{ $errors->first('type') }}</strong>
</span>
@endif
</div>
</div>
That works just fine.
I'm no trying to allow users to edit a particular form. I can get other sections like title and photo by assigning a value to the input and calling the data like this
<input id="Address" type="text" class="form-control" name="address" value="{{$Advert->address }}" required autofocus>
But when I attempt to do something similar on a select option, nothing appears. This is a dropdown on the edit page.
<div class="form-group row">
<label for="type" class="col-md-3 col-form-label text-md-right">Type</label>
<div class="col-md-9">
<select class ="form-control" id="type" name="type" value="{{$Advert->type}}">
<option></option>
<option>Apartment</option>
<option>House</option>
<option>Studio</option>
<option>Flat</option>
</select>
@if ($errors->has('type'))
<span class="invalid-feedback">
<strong>{{ $errors->first('type') }}</strong>
</span>
@endif
</div>
</div>
Upvotes: 0
Views: 2553
Reputation: 53
Like it was suggested before I would use Laravel Collective Forms; like this:
{!! Form::select('type',$selectOptions,null,['id' =>'type','class' => 'form-control'])!!}
The variable $selectOptions would have all the options:
$selectOptions = [
'' => 'Select',
'Apartment' => 'Apartment',
'House' => 'House',
'Studio' => 'Studio',
'Flat' => 'Flat'
];
It will be this easy to do. Offcourse everything should be inside a form.
{!! Form::open() !!}} or {!! Form::model($model) !!}
Hope it helps.
Upvotes: 0
Reputation: 3543
You need to use selected
attribute on your option
element instead of assigning the value directly to select
:
<select class ="form-control" id="type" name="type">
<option value="">Select</option>
<option {{ $Advert->type == 'Apartment' ? 'selected':'' }}>Apartment</option>
<option {{ $Advert->type == 'House' ? 'selected':'' }}>House</option>
<option {{ $Advert->type == 'Studio' ? 'selected':'' }}>Studio</option>
<option {{ $Advert->type == 'Flat' ? 'selected':'' }}>Flat</option>
</select>
But I suggest you use Laravel Collective Forms
to have a better handling of form and it's elements
Upvotes: 2