So i am working this project that has a feature of adding multiple rows in one submit, I am Using jQuery append() to add input rows, but then if one of the request did not comply to the required rules in validation the appended row is not showing and not returning its old input. here's my code.
My View
<tr class="table_row" id="appended_tr">
<td>
<select id="menu" name="menu[]" class="form-control">
<option>Select</option>
#foreach($menus as $data)
<option value="{{ $data->menu_id }}" {!! old('menu.0') == $data->menu_id ? 'selected' : '' !!}>{{ $data->name }}</option>
#endforeach
</select>
<small class="text-danger">{{ $errors->first('menu.0') }}</small>
</td>
</tr>
here's My javascript
$(document).ready(function() {
$("#add_row").on("click", function() {
$('select').select2('destroy');
var count = $('tr[id="appended_tr"]').length;
console.log();
var content ='<tr id="appended_tr">' +
'<td>' +
'<select id="menu" name="menu[]" class="form-control">' +
'<option>Select</option>' +
'#foreach($menus as $data)' +
'<option value="{{ $data->menu_id }}"' +
'{!! old("menu.1") == $data->menu_id ? "selected" : "wew" !!} >{{ $data->name }}</option>' +
'#endforeach' +
'</select>' +
'<small class="text-danger">{{ $errors->first('menu.1') }}</small>' +
'</td>' +
'</tr>';
$("#table_body").append($(content));
$('select').select2({width:400});
});
});
Here's my rules
public function rules(){
foreach($this->request->get('menu') as $key => $value){
$rules['menu.'.$key] = 'required';
}
return $rules;
}
Related
I use add/remove input fields with jquery and have problem when I want to update the values.
In the store() method foreach loop fetches all input fields that I added, while in the update() method foreach loop fetched only first input.
How can I fix this?
I have two tables "attributes(id,name)" and "attribute_option(id,attribute_id,attribute_value").
In edit.balde.php
<script type="text/javascript">
$("#add").click(function(){
addRow();
}}
function addRow(){
$("optionsTable").append('<tr><td><input type="text" name="value[]" class="form-control"</td><td><button type="button" class="remove-tr">Remove</button></td></tr>);
};
$(document).on('click','.remove-tr', function(){
$(this).parents('tr).remove();
});
</script>
<button type="button" id="add">Add row</button>
#foreach($attribute_options as $key=>$option)
<tr>
<td>
<input type="hidden" name="option_id[]" value="{{ $option->id }}">
<input type="text" name="value[]" value="{{ $option->attribute_value }}">
</td>
<td>
<button type="button" class="remove-tr">Remove</button>
</td>
</tr>
#endforeach
in my controller action update()
if($request->has('value)){
$options = $request->value;
$option_id = $request->option_id;
foreach($options as $value){
AttributeOption::where('id','=',$option_id)->update(array(
'attribute_value' => $value
));
}
}
Because $option_id is also an array and therefore also must be read as an array:
if($request->has('value')){
$options = $request->value;
$option_id = $request->option_id;
foreach($options as $key => $value){
AttributeOption::where('id','=',$option_id[$key])->update(array(
'attribute_value' => $value
));
}
}
I'm facing one issue about multi-select.
onchange i'm runnig ajax and on ajax success option appends to multiselect.
but at the time of edit i'm not able to trigger ajax and not able to show selected option in multiselect.
please check my code
form fleds
<div class="form-group {{ $errors->first('preferred_city', 'has-error') }}">
<label class="control-label col-lg-2">Preferred City
: </label>
<div class="col-lg-10">
<select name="preferred_city[]" class="form-control" id="preferred_city" multiple="multiple" style="color: #333">
#foreach($cities as $preferred_city)
#if(!empty($studentsDetails->preferred_city))
<option value="{{$preferred_city->id}}" {{ (in_array($preferred_city->id,\GuzzleHttp\json_decode($studentsDetails->preferred_city) )) ? 'selected' : '' }}>{{$preferred_city->city_name}}</option>
#else
<option value="{{$preferred_city->id}}">{{$preferred_city->city_name}}</option>
#endif
#endforeach
</select>
<span class="help-block">{{ $errors->first('preferred_city', ':message') }}</span>
</div>
</div>
<div class="form-group {{ $errors->first('collage_preferences', 'has-error') }}">
<label class="control-label col-lg-2">College Preferences
: </label>
<div class="col-lg-10">
<select id="collage_preferences" name="collage_preferences[]" class="form-control" multiple="multiple">
</select>
<span class="help-block">{{ $errors->first('collage_preferences', ':message') }}</span>
</div>
</div>
js
collage id's i'm fetching from database
var collage_pref = {!! $studentsDetails->collage_preferences !!}
I'm triggering preferred_city on page load
$(document).ready(function(){
if(studentsDetails !=null){
$('#preferred_city').trigger('change');
// $('#pic_file').trigger('change');
}
});
$('#preferred_city').on('change',function(){
$("#collage_preferences").multiselect('rebuild');
$.ajax({
url:'{{route('student.getInstituteslists')}}',
type:'get',
async: false,
data:{grad_course:$('#grad_course').val(),preferred_city:$('#preferred_city').val()},
success:function(e){
$('#collage_preferences').multiselect('refresh');
e.forEach(function(inst){
var data = '';
data +='<option value="'+ inst.id+'" >'+ inst.institute_name+'</option>';
$('#collage_preferences').append(data);
});
$('.collage_preferences').multiselect('rebuild');
}
});
});
$data = [];
$data['airlines'] = '';
$airlines = (Airline::select('Code','Name')->get())->toArray();
$myairlines = BlackoutAirline::where('SupplierId',$request->SupplierId)->pluck('AirlineCode')->toArray();
foreach($airlines as $airline) {
if(in_array($airline['Code'], $myairlines) ){
$data['airlines'] .= '<option value="'.$airline['Code'].'" selected>'.$airline['Name'].'</option>';
}
else{
$data['airlines'] .= '<option value="'.$airline['Code'].'">'.$airline['Name'].'</option>';
}
}
return json_encode($data);
I try to validate in array by using 'id_s.*' => 'required', not sure why t didnt work
UPDATED I add my jquery append , in my controller I use loop which I want to require id_s
In my html
<select id="custom-select" class="form-control custom-select" name="id_s[]" >
<option disabled="true" selected="true" name="id_s[]" value="choose">choose</option>
#foreach($subject as $s)
<option value="{{$s->ID}}" name=id_s[]>{{$s->NAME}} / {{$s->CREDIT}} </option>
#endforeach
</select>
$(document).ready(function() {
$('#add-form').click(function() {
i++;
id_i++;
$('#add-me').append(
'<tr>'+
'<td>'+
'<select id="custom-select" name="id_s[]" class="form-control custom-select"><option disabled="true" selected="true" name="id_s[]" value="choose">choose</option>#foreach($subject as $s)<option value="{{$s->ID}}" name=id_s[]>{{$s->NAME}} / {{$s->CREDIT}}</option>#endforeach</select>'
+'</td>'
+'<td>'
+'<button id="'+i+'" type="button" class="btn btn-danger delegated-btn">Delete</button>'
+'</td>'
+'</tr>'
);
$('button.btn.btn-danger').click(function() {
var whichtr = $(this).closest("tr");
whichtr.remove();
});
});
});
For the select you will not need to do array in the name and you don't need to add name to the options as well :
<select id="custom-select" class="form-control custom-select" name="id_s" >
<option disabled="true" selected="true" value="choose">choose</option>
#foreach($subject as $s)
<option value="{{$s->ID}}" >{{$s->NAME}} / {{$s->CREDIT}}</option>
#endforeach
</select>
and the validation like this :
'id_s' => 'required|not_in:choose'
This is my view index page
<div class="form-group">
{!! Form::label('cname','Clients: ') !!}
{!! Form::select('cname',[''=>'Select Category']+$client,null,['class'=>'form-control selectpicker']) !!}
<span class="input-group-btn">
<a class="btn btn-primary" href="">Edit</a>
</span>
</div>
Controller:
public function index() {
$client = Client::pluck('cname','clientid')->all();
return view('client.index', compact('client'));
}
How can i get select item from dropdown and from button click send the selected details to edit view?
You can do something like this
// Controller
public function index()
{
$roles = Roles::all();
$selectedRole = User::first()->role_id;
return view('my_view', compact('roles', 'selectedRole');
}
And then in your view
<select class="form-control m-bot15" name="role_id">
#if ($roles->count())
#foreach($roles as $role)
<option value="{{ $role->id }}" {{ $selectedRole == $role->id ? 'selected="selected"' : '' }}>{{ $role->name }}</option>
#endif
</select>
I want to create a zone which contain few cities. So I decided to use jQuery Select2
Here is my create form multiple selection
<div class="form-group {{ $errors->has('cities') ? 'has-error' : '' }}">
<label>Tentukan Kota</label>
<select name="cities[]" class="city form-control" data-placeholder="Pilih Kota" style="width: 100%;" multiple="multiple">
#foreach($cities as $city)
<option value="{{ $city->id }}">{{ $city->name }}</option>
#endforeach
</select>
</div>
I can multiple select just like in documentation.
Here is my controller which handle display create form
public function zone_create()
{
$cities = City::where('zone_id', null)->get();
return view('backend.admin.pricings.zone_create', compact('cities'));
}
The relationship is One Zone Has Many City.
class Zone extends Model
{
protected $fillable = [
'name',
];
public function cities(){
return $this->hasMany(City::class);
}
}
The city belongs to zone
class City extends Model
{
protected $fillable = [
'zone_id',
'name',
];
public function zone(){
return $this->belongsTo(Zone::class);
}
}
Here is my edit method
public function edit($id)
{
$zone = Zone::find($id);
$cities = City::all();
return view('backend.admin.pricings.zone_edit', compact('zone', 'cities'));
}
Here is my edit form so far
<div class="form-group {{ $errors->has('cities') ? 'has-error' : '' }}">
<label>Tentukan Kota</label>
<select name="cities[]" class="city form-control" data-placeholder="Pilih Kota" style="width: 100%;" multiple="multiple">
//load option from cities table
//set selected the city belongs to zone
//the other city which don't belong to zone still here for option
</select>
</div>
But how I can populate my edit form (multiple selection) with City belongs to zone?
Just like this in my view
<select name="cities[]" class="city form-control" data-placeholder="Pilih Kota" style="width: 100%;" multiple="multiple">
#foreach($cities as $city)
#if(in_array($city->id, $zoneCityIds))
<option value="{{ $city->id }}" selected="true">{{ $city->name }}</option>
#else
<option value="{{ $city->id }}">{{ $city->name }}</option>
#endif
#endforeach
</select>
and like this in my controller
public function zone_edit($id)
{
$zoneCityIds = [];
$zone = Zone::find($id);
$cities = City::all();
foreach($zone->cities as $zoneCity)
{
$zoneCityIds[] = $zoneCity->id;
}
return view('backend.admin.pricings.zone_edit', compact('zone', 'cities', 'zoneCityIds'));
}
actually it's jus about option tag selected="true"
for multiple values simply use
<div class="form-group">
{!! Form::label('Categories') !!}<br />
{!! Form::select('categories[]', $cost_centers,
$post->categories->pluck('id')->toArray(),
['class' => 'form-control',
'multiple' => 'multiple']) !!}
</div>
In your edit function you can get all the cities of that particular zone
$zone_cities = implode(',',$zone->cities->lists('name')->toArray());
and pass $zone_cities in your view.
return view('backend.admin.pricings.zone_edit', compact('zone', 'cities','zone_cities'));
You will have to use Form Model binding in your view
Read about laravel collective form model binding [here].1
You will open your form like this
Your Edit form will be like this
{!! Form::label('cities','Cities: ') !!}
{!! Form::text('cities',$zone_cities,['class'=>'input','id'=>'cities','aria-required'=>'true','data-seperator'=>',']) !!}