How to add "selected" on the dropdown option in Laravel?
I am doing editing profile. In the profile I have a dropdown list, the options are pulled from database, like this.
//Controller
$gender= Gender::lists('gender', 'id');
//View
{{ Form::select('gender', $gender, null, array('class' => 'form-control')) }}
//Output
<select class="form-control" name="gender"><option value="1">Male</option><option value="2">Female</option></select>
My question: If the user is female, how to add "selected" in the female option if the user has saved female in database before, so that I can show the gender when the page is loaded?
You can set the default value at the 3rd parameter.
Assume Female id is 2
{{ Form::select('gender', $gender, 2, array('class' => 'form-control')) }}
If you already has a $user with sex_id attribute(or your sex column), You can pass it to the Form::select as well.
{{ Form::select('gender', $gender, $user->sex_id, array('class' => 'form-control')) }}
http://laravel.com/docs/4.2/html#drop-down-lists
Related
I´m trying to create a form select in laravel.
I was created perfectly, but in my view first option is 0 and one first option empty
I need to remove this 0 and option empty, but i don't know how i can do it, this is my actual code:
<div class="form-group row ">
{!! Form::label('restaurant_id', trans("lang.blog_restaurant_id"),['class' => 'col-3 control-label text-right']) !!}
<div class="col-9">
{!! Form::select('restaurant_id', [null => null, $restaurant], null, ['class' => 'select2 form-control']) !!}
<div class="form-text text-muted">{{ trans("lang.blog_restaurant_id_help") }}</div>
</div>
</div>
$restaurant it's one data array for to fill my select. I read that with first option null put selected option empty, but generate a empty option and 0.
Thanks for help me.
UPDATE
Laravel include optgroup into Form::select that it´s triggering my 0 this it´s the problem. i need delete optgroup
<select class="select2 form-control select2-hidden-accessible" id="restaurant_id" name="restaurant_id" tabindex="-1" aria-hidden="true">
<option value="" selected="selected"></option>
<optgroup label="0">
<option value="17">Foody Lindgren, Cremin and Erdman gdfgfg fgfg fg fgfg g fggf</option>
<option value="28">restaurante de pruebas</option>
<option value="29">probando</option>
<option value="30">pincho de castilla2</option>
</optgroup>
update 2
getting list of restaurant:
$restaurant = $this->restaurantRepository->pluck('name', 'id');
this is result in blade:
{"17":"Foody Lindgren, Cremin and Erdman gdfgfg fgfg fg fgfg g fggf","28":"restaurante de pruebas","29":"probando","30":"pincho de castilla2"}
Add toArray():
$restaurant = $this->restaurantRepository->pluck('name', 'id');
$restaurant->toArray();
same result
Please try this. Add blank key and blank value like below.
{!! Form::select('restaurant_id', ["" => "", $restaurant], null, ['class' => 'select2 form-control']) !!}
It seems that the $restaurant is an array.
So, you'd better do something like this:
Form::select('restaurant_id', $restaurant, null, ['class' => 'select2 form-control'])
you may need a proper mapping for your $restaurant in your controller, depending on what you need, like adding an empty option in the beginning.
// in Controller
$options = ["" => "select"] + $restaurant;
// In view
Form::select('restaurant_id', $options, null, ['class' => 'select2 form-control'])
update 2
You should make sure to send the $restaurant as an array:
$restaurant = $this->restaurantRepository->pluck('name', 'id')->toArray();
For adding an empty option:
$restaurant = ["" => "select"] + $restaurant;
There is also another option:
You can even add the select box manually instead of using Form::select.
<select class="select2 form-control" id="restaurant_id" name="restaurant_id">
<option value="" selected="selected"></option>
#foreach($restaurant as $value => $option)
<option value="{{ $value }}">{{ $option }}</option>
#endforeach
</select>
I want the select dropdown value to be selected in my edit form.
In my controller
public function edit($id)
{
$vedit = DB::table('vehicles')->where('id', $id)->first();
$cartype= DB::table('car_category')->pluck('cartype');
return view('vehicles.edit', compact('vedit','cartype'));
}
In view
{{ Form::label('Vehicle Type', 'Vehicle Type') }}
<select name="vehicle_type" class="form-control">
#foreach($cartype as $cartypes)
<option value="{{ $cartypes}}">{{ $cartypes}}</option>
#endforeach
</select>
How can I achieve this?
You can add selected attribute if it's the choosen one like this :
{{ Form::label('Vehicle Type', 'Vehicle Type') }}
<select name="vehicle_type" class="form-control">
#foreach($cartype as $cartypes)
<option value="{{ $cartypes}}" {{ $cartypes == $vedit->vehicle_type ? 'selected' : ''}}>{{ $cartypes}}</option>
#endforeach
</select>
What version of Laravel are you using ? Looks like you're using Laravel Collective Form facade.
In that case, this should work fine:
{!! Form::label('Vehicle Type', 'Vehicle Type') !!}
{!! Form::select('vehicle_type', $cartype, $vedit->vehicle_type ?: old('vehicle_type), ['class' => 'form-control']) !!}
Assuming $vedit->vehicle_type is your previously stored vehicle type. So it will pre-select that when editing. In case of creating new, old('vehicle_type') should persist the previously selected value on failed validations.
By calling pluck() an array of values is already returned for the car types.
So just use it like this natively with Laravel Collective:
{!! Form::label('Vehicle Type', 'Vehicle Type') !!}
{!! Form::select('vehicle_type', $cartype, null, ['class' => 'form-control']) !!}
Note, I have also changed your double curly braces. The double curly braces escape the output - given the Form facade returns HTML code, you want this to be unescaped.
More info on generating drop down lists with Laravel Collective; https://laravelcollective.com/docs/5.4/html#drop-down-lists
Edit show currently selected value and old value if form fails validation:
{!! Form::label('Vehicle Type', 'Vehicle Type') !!}
{!! Form::select('vehicle_type', $cartype, old('vehicle_type', $vedit->vehicle_type), ['class' => 'form-control']) !!}
A database table has two fields first_name and last_name.
If I want to fill a dropdown box i can use this code:
{!! Form::select('driver_id', App\Driver::pluck('first_name','id'), null, ['class' => 'form-control']) !!}
But if I want concat two fileds i should use a SelectRow on my model:
{!! Form::select('driver_id', App\Driver::select(DB::raw("CONCAT(first_name,' ', last_name) AS full_name, id"))->pluck('full_name','id'), null, ['class' => 'form-control']) !!}
But this solution does not works and this is what i get:
<select class="form-control" name="driver_id">
<option value="">Autista...</option>
<option value="11"> </option>
<option value="12"> </option>
<option value="13"> </option>
.....
</select>
That is.... the select does not get "full_name" filed but get the "id" field.
How to solve ?
I think you can try this:
{{ Form::select('driver_id', App\Driver::select(DB::raw("CONCAT(first_name,' ', last_name) AS full_name, id"))->lists('full_name','id'), null, ['class' => 'form-control']) }}
Hope this work for you!
Try This in your blade file:
App\Driver::select(
DB::raw("CONCAT(first_name,' ',last_name) AS full_name"),'id')
->pluck('full_name', 'id');
SOLUTION
The problem is the underscore character in the alias field name "full_name".
This code works fine:
App\Driver::selectRaw("CONCAT(first_name,' ',last_name) as fullname ,id")->pluck("fullname", "id")
Thanks everyone.
Controller method:
public function edit($id){
$match2 = Match::pluck('team_a_id', 'id');
return view('admin.accept.edit', compact('match2'));
}
And view file:
{{ Form::select('matches_id', $match2, null, ['class' => 'form-control']) }}
And my table:
Table from model Match (table name: matches):
Table from model Team (table name: teams):
Table teams is connected (references) with table matches( team_a_id and team_b_id is connected with table teams). The select method with view returned me only ID with tables:
I need have team_name with table teams not id.
When I change method pluck:
$match2 = Match::pluck('id', 'id');
And view:
{{ Form::select('matches_id', Team::find($match2)->team_a_id." vs. ".Team::find($match2)->team_b_id, null, ['class' => 'form-control']) }}
Laravel returned error:
Invalid argument supplied for foreach() (View:
C:\xampp\htdocs\football\football\resources\views\admin\accept\edit.blade.php)
This is metohd edit so I must have highlighted record that was previously selected.
Ok I repair this. I write method:
public function edit($id){
$match = Match::select()->orderBy('updated_at', 'asc')->get();
$selectedMatch = DB::table('usermatches')->find($id)->matches_id;
return view('admin.accept.edit', compact('match', 'selectedMatch'));
}
And view:
<select name="matches_id" id="matches_id" class="form-control selectpicker" data-live-search="true" data-size="5">
<option value=0>Wybierz wydarzenie</option>
#foreach($match as $role)
<option value="{{ $role->id }}" {{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}>
{{ Team::find($role->team_a_id)->team_name }} vs. {{ Team::find($role->team_b_id)->team_name }} ({{$role->date}}; <?php echo date('G:i',strtotime($role->time)); ?> | Liga {{ League::find($role->league_id)->name }} | {{ Sport::find($role->sport_id)->name }})
</option>
#endforeach
</select>
In model view I compare id with two tables and it working ;)
{{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}
I'm fairly new to Symfony2 and am working with the form builder trying to create a dropdown menu from the database. I can populate the dropdown without problem but each options value attribute just gets set to a number when it needs to be set to either the options text or no value attribute but I can't find anything in the documentation about setting the value.
$builder->add('institution', 'entity', array(
enter code here 'class' => 'JacksonFramesStoreBundle:Institution',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('i')
->where('i.type = :type')
->setParameter('type', 'University');
},
'empty_value' => 'Select:',
'empty_data' => null,
));
This outputs:
<select id="selectUniversity" name="selectUniversity">
<option value="0"></option>
<option value="1">Australian Catholic University</option>
<option value="2">Australian National University</option>
<option value="3">Bond University</option>
</select>
EDIT - this is the relevant section of the twig
<!-- University Panel -->
<div id="uniPanel" style="display:none;">
<p>{{ form_label(form.institution) }}<br />
<span class="inputLine">
{{ form_errors(form.institution) }}
{{ form_widget(form.institution) }}
</span>
</p>
</div>
In the controller, after if ($form->isValid()), try using:
$value = ($entity->getInstitution()) ? $entity->getInstitution()->getId() : null);
I don't really know if I really understood your question