Post checkbox value's when using dynamic fields - php

I'm building a task list where I can add and delete fields dynamically for each user. The problem I have, is saving the data from the checkbox.
I'm using the following code:
<form>
#foreach($tasks as $task)
<div class="col-md-9">
<input id="taskfield" name="dynamic[]" value="{{ $task->name }}" class="form-control field" type="text">
</div>
<div class="col-md-3">
<div class="slideOne">
<input type="checkbox" value="1" id="slideOne" name="check[]" #if($task->finished == 1) checked #endif/>
<label for="slideOne"></label>
</div>
</div>
#endforeach
/*The JS will add the new items here. JS example:*/
<div class="col-md-9">
<input id="taskfield" name="dynamic[]" value="{{ $task->name }}" class="form-control field" type="text">
</div>
<div class="col-md-3">
<div class="slideOne">
<input type="checkbox" value="1" id="slideOne" name="check[]" #if($task->finished == 1) checked #endif/>
<label for="slideOne"></label>
</div>
</div>
</form>
For saving it dynamically, I'm using this in my controller:
DB::table('tasks')->where('user_id', '=', $_POST['uid'])->where('week', '=', $_POST['week'])->where('year', '=', $_POST['year'])->delete();
if(isset($_POST['dynamic'])){
$takenvdweek = $_POST['dynamic'];
$finished = $_POST['check'];
var_dump($finished);
foreach($takenvdweek as $key => $value) {
DB::insert('insert into tasks (name, finished, user_id, week, year) values (?, ?, ?, ?, ?)', array($value, $finished[$key], $_POST['uid'], $_POST['week'], $_POST['year']));
}
}
So my Saving method requires always a value for the checkbox, 0 when unchecked and 1 when checked. I tried it with a hidden field with a 0, but it didn't work because the 0 was always in the POST array. Also when I click the a label, the first foreach label is changing, not the second where I click on. I tried to fix this with a class, but was no success.
Edit:
The foreach is for tasks that exists, but I can also add new items with a piece op JS, they are also inside the form, so I can't give them a foreach-id. I updated my question with the JS example.

Try to set the task id as index of dynamic and check
See below
#foreach($tasks as $task)
<div class="col-md-9">
<input id="taskfield" name="dynamic[$task->id]" value="{{ $task->name }}" class="form-control field" type="text">
</div>
<div class="col-md-3">
<div class="slideOne">
<input type="checkbox" value="1" id="slideOne" name="check[$task->id]" #if($task->finished == 1) checked #endif/>
<label for="slideOne"></label>
</div>
</div>
#endforeach
--Edit---
if task id is not available then you can set index like below
$index = 0;
#foreach($tasks as $task)
<div class="col-md-9">
<input id="taskfield" name="dynamic[$index]" value="{{ $task->name }}" class="form-control field" type="text">
</div>
<div class="col-md-3">
<div class="slideOne">
<input type="checkbox" value="1" id="slideOne" name="check[$index]" #if($task->finished == 1) checked #endif/>
<label for="slideOne"></label>
</div>
</div>
$index++;
#endforeach

This should do:
#foreach($clubs as $club)
<input type="checkbox"
id="{{$club->getCode()}}"
name="clubs[]"
value="{{$club->getId()}}" /> {{$club->getName()}}<br>
#endforeach

Related

How to store an array as single row for each value in my database

the whole idea is that when a user click on checkbox and save, the form should be submitted with an array containing the checked values, and save them in the database as single row for each value. i don't know if this is possible but i'm sure you guys have a solution or can help me?
and here's my form:
<div class="">
<form style="width: 70%" method="POST" action="{{ URL('/admin/projects/services/save') }}"
enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" id="id" value="{{ #$id }}">
<input type="hidden" name="projectid" id="projectid" value="{{ #$projectid }}">
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Selected Services: <span class="red">*</span></p>
</div>
<div class="col-9">
<input type="text" id="selectedServices" name="selectedServices" value="" readonly>
</div>
</div>
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Select a service: <span class="red">*</span></p>
</div>
<div class="col-9">
#foreach ($services as $service)
<input type="checkbox" name="service" value="<?php echo stripslashes($service->id); ?>">
<label for="service"><?php echo stripslashes($service->name); ?></label>
<br>
<hr>
#endforeach
#error('service')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
</div>
<div class="row topSpacerHuge">
<div class="col-12 textRight">
<button type="button"
onclick="window.location='{{ url('admin/projects/services/index/'.$projectid) }}'"
class="goBackBtn">Cancel</button>
<input class="saveBtn" id="saveBtn" type="submit" value="Save">
</div>
</div>
</form>
</div>
and my script to get checkboxes value:
<script>
$(function() {
$("input:checkbox[name='service']").click(function() {
$value = [];
$.each($("input:checkbox[name='service']:checked"), function() {
$value.push($(this).val());
$array = $value.join();
});
// console.log(value.join(", "));
$("#selectedServices").val($array);
})
});
</script>
for implementing checked values I recommend to use the select tag
and you can give A name attribute with [] and it will collect all of your data
for example , look at my project's file which I'm trying to collect name of some users :
<select name="users[]" id="example-with-maxHeight" class="multiselect-group" multiple >
#foreach($users as $user)
<option #if($user->average < $averageParticipate )class="alert-danger" #endif value="{{$user->id}}">{{$user->name}} - {{$user->average}}</option>
#endforeach
</select>
have attention to users[] in name attribute
now in your request you can access all of your checked items .
if we look at your code ,can be some thing like this :
<label for="service"><?php echo stripslashes($service->name); ?></label>
<select name="services[]" id="" class="multiselect-group" multiple >
#foreach($users as $user)
<option value = "{{$sevice->id}}"> <?php echo stripslashes($service->name); ?></option>
#endforeach
</select>
now in your controllers you can access them :
request->get('services');
it will give you back an array of selected items .
Notice that id attribute helps me to interact with my java script code
you can rename it to yourselves .

2 values in checkbox type

I want make function who can switch 2 values - Yes and No in Database. Now i have checkbox type who get me 1 value - "Yes" and when is not checked dont give me value. I want make in controller to switch when I dont get value to switch to "No" value. Now my function work, but change only last result, not this who i want. https://i.imgur.com/os12J8p.png & https://i.imgur.com/PR3K0lT.png. This is my code
<form method="post" action="/adminpanel/hofswitch">
#csrf
<div class="card-body">
#foreach($char as $value)
<div class="card-body">
#if($value->status == "Yes")
<input type="checkbox" name="switch[]" value="{{$value->id}}" checked data-bootstrap-switch data-off-color="danger" data-on-color="success">
<div class="form-group">
<label class="col-form-label" for="inputSuccess"><i class="fas fa-check"></i> Character Class</label>
<input type="text" name="class[]" value="{{$value->class}}" class="form-control is-valid" id="inputSuccess" readonly="true" placeholder="{{$value->class}}">
</div>
#else
<input type="checkbox" name="switch[]" value="{{$value->id}}" data-bootstrap-switch data-off-color="danger" data-on-color="success">
<div class="form-group">
<label class="col-form-label" for="inputError"><i class="far fa-times-circle"></i> Character Class</label>
<input type="text" name="class[]" value="{{$value->class}}" class="form-control is-invalid" id="inputError" readonly="true" placeholder="{{$value->class}}">
</div>
#endif
</div>
#endforeach
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary col-12">Submit</button>
</div>
</form>
and Controller
public function hof_switch(Request $request) {
$count = count(collect($request->get('switch')));
for($i = 0; $i < $count; $i++) {
$switch = $request->switch[$i] ?? null;
if ($switch == true) {
$switch = "Yes";
} else {
$switch = "No";
}
$update = DB::connection('XWEB')->table('XWEB_HOF')
->where('id', $request->switch[$i])
->update(
[
'status' => $switch,
]);
}
return redirect()->back()->withSuccess('You have switch this class successfully!');
}
Fews days ago I've been in similar problem
Put a hidden input with same name, and then try to POST it.
If the checkbox is checked, than the value will be send 1.
And If the checkbox isn't checked, than the value will be send only 0.
<form>
<input type="hidden" name="switch[]" value="0">
<input type="checkbox" name="switch[]" value="1">
</form>

How to get input radio name with many different name in laravel

In this project, i make something like online test. my question is how to get radio name with many different name in laravel ? i use id to different their name so but i cant get their name in controller.
this is my view
<form action="{{url('kumpulkan')}}" method="POST" class="responsive-form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#if(Session::get('jurusan') == Multimedia)
<?php
$no = 1;
;?>
#foreach($soal_multimedia as $row)
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="wrapper-soal">
<div class="pertanyaan">
<span class="no-soal"><?php echo $no++ ;?>. </span> <span class="teks-soal">{{$row->soal}}</span>
</div>
<div class="jawaban">
<input type="number" readonly="readonly" name="id_soal" value="{{$row->id}}" hidden="hidden">
<div class="jawaban-item jawaban-a">
<input type="radio" name="jawaban_{{$row->id}}" value="{{$row->jawaban_a}}"> {{$row->jawaban_a}}
</div>
<div class="jawaban-item jawaban-b">
<input type="radio" name="jawaban_{{$row->id}}" value="{{$row->jawaban_b}}"> {{$row->jawaban_b}}
</div>
<div class="jawaban-item jawaban-c">
<input type="radio" name="jawaban_{{$row->id}}" value="{{$row->jawaban_c}}"> {{$row->jawaban_c}}
</div>
<div class="jawaban-item jawaban-d">
<input type="radio" name="jawaban_{{$row->id}}" value="{{$row->jawaban_d}}"> {{$row->jawaban_d}}
</div>
</div>
</div>
</div>
</div>
#endforeach
#endif
<button class="btn btn-default btn-lg">Selesai</button>
</form>
this is my controller
public function Postkumpulkan(Request $request)
{
$insert = array();
$insert['id_soal'] = $request->get('id_soal');
$insert['nama'] = Session::get('nama');
$insert['no_peserta'] = Session::get('no_peserta');
$insert['sekolah'] = Session::get('sekolah');
$insert['jurusan'] = Session::get('');
$insert['jawaban'] = $request->get('jawaban_{{$row->id}}');
}
i think you would better use checkbox and instead of this naming jawaban_{{$row->id}}
use this kind jawaban[{{$row->id}}] in this case you can get all jawabans in one array
like this :
$insert['jawaban'] = $request->get('jawaban');
Since I assume you intend to make your radio buttons to work as a radiogroup (yes, where you can only choose 1) and since that is how radio buttons work, you should just give the same name for all the radio buttons.
<div class="jawaban">
<input type="number" readonly="readonly" name="id_soal" value="{{$row->id}}" hidden="hidden">
<div class="jawaban-item jawaban-a">
<input type="radio" name="jawaban" value="{{$row->jawaban_a}}"> {{$row->jawaban_a}}
</div>
<div class="jawaban-item jawaban-b">
<input type="radio" name="jawaban" value="{{$row->jawaban_b}}"> {{$row->jawaban_b}}
</div>
<div class="jawaban-item jawaban-c">
<input type="radio" name="jawaban" value="{{$row->jawaban_c}}"> {{$row->jawaban_c}}
</div>
<div class="jawaban-item jawaban-d">
<input type="radio" name="jawaban" value="{{$row->jawaban_d}}"> {{$row->jawaban_d}}
</div>
</div>
Then you can just retrieve it in the controller:
$insert['jawaban'] = $request->get('jawaban');
It will retrieve the chosen radio button.

fill fields with auth user info when checkbox is checked

When the checkbox "Fill with auth user info" is clicked I want to populate the fields with the auth user info (name and surname) but it's not working. When the checkboxes are clicked is not working the fields are not populated with the auth user info.
What I have for now is in, https://jsfiddle.net/LahL166o/2/ the auth user info appears in this span
<span id="userData" data-name="John"
data-surname="Keane"></span>
The issue should be how to get the ticket type name in the jquery with laravel because as it is ther is no id with "name" or "surname" the result ids are: "namegeneral_1" and "surnamegeneral_1".
laravel form:
<form method="post" id="step1" action="">
{{csrf_field()}}
#if (!empty($allParticipants))
#if($allParticipants == 1)
<p>Fill all fields.</p>
#foreach($selectedRtypes as $k => $selectedRtype)
#foreach(range(1,$selectedRtype['quantity']) as $val)
<h6 class="text-heading-blue mb-3 pb-2 font-weight-bold">Participant - {{$val}} - {{$k}} </h6>
#if ($loop->first)
<div class="form-check">
<input class="form-check-input" id="fill_auth_info" type="checkbox">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Fill with auth user info.</span>
</label>
</div>
#endif
<span id="userData" data-name="{{ auth()->user()->name }}"
data-surname="{{ auth()->user()->surname }}"></span>
<div class="form-group font-size-sm">
<label for="participant_name" class="text-gray">Name</label>
<input type="text" id="name" name="participant_name[]" required class="form-control" value="">
</div>
<div class="form-group font-size-sm">
<label for="participant_surname" class="text-gray">Surname</label>
<input type="text" id="surname" required class="form-control" name="participant_surname[]" value="">
</div>
#endforeach
#endforeach
#endif
#else
<p>Is not necessary additional info.</p>
#endif
<input type="submit" href="#step2free"
id="goToStep2Free" class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
Html result:
<form method="post" id="step1form" action="">
<input type="hidden" name="_token" value="">
<h6 class="text-heading-blue mb-3 pb-2 font-weight-bold">Participant - 1 - general </h6>
<div class="form-check">
<input class="form-check-input" name="fill_with_auth_info" id="fill_auth_infogeneral_1"
data-id="general_1" type="checkbox">
<label class="form-check-label d-flex align-items-center"
for="fill_auth_info1">
<span class="mr-auto">Fill with auth user info.</span>
</label>
</div>
<span id="userData" data-name="John"
data-surname="Keane"></span>
<div class="form-group font-size-sm">
<label for="namegeral_1" class="text-gray">Name</label>
<input type="text" id="namegeral_1" name="participant_name[]" required class="form-control" value="">
</div>
<div class="form-group font-size-sm">
<label for="surnamegeneral_1" class="text-gray">Surname</label>
<input type="text" id="surnamegeneral_1" required class="form-control" name="participant_surname[]" value="">
</div>
<input type="hidden" name="all_participants" value="1" />
<input type="hidden" name="rtypes[]" value="1"/>
<h6 class="text-heading-blue mb-3 pb-2 font-weight-bold">Participant - 1 - re </h6>
<div class="form-check">
<input class="form-check-input" name="fill_with_auth_info" id="fill_auth_infore_1"
data-id="re_1" type="checkbox">
<label class="form-check-label d-flex align-items-center"
for="fill_auth_info1">
<span class="mr-auto">Fill with auth user info.</span>
</label>
</div>
<span id="userData" data-name="John"
data-surname="Keane"></span>
<div class="form-group font-size-sm">
<label for="namere_1" class="text-gray">Name</label>
<input type="text" id="namere_1" name="participant_name[]" required class="form-control" value="">
</div>
<div class="form-group font-size-sm">
<label for="surnamere_1" class="text-gray">Surname</label>
<input type="text" id="surnamere_1" required class="form-control" name="participant_surname[]" value="">
</div>
<input type="hidden" name="all_participants" value="1" />
<input type="hidden" name="rtypes[]" value="2"/>
<input type="submit" href="#step2free"
id="goToStep2Free" class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
jQuery:
let userData = $('#userData');
$("input[name = 'fill_with_auth_info']").on('click', function(e) {
let checked = $(this).is(':checked');
if (checked) {
$('#name').val(userData.data('name'));
$('#surname').val(userData.data('surname'));
} else {
$('#name').val(userData.data(''));
$('#surname').val(userData.data(''));
}
});
I think you may have a number of issues that are preventing this from working. I think most are stemming from your looping and accidentally assigning the same id to many items.
However, the code displayed above is a bit confusing as well - the blade file should produce something different from the HTML you show. I assume this was a later iteration? I will speak to the blade file, as it is easier to see, since its smaller.
To help get this working, I suggest the following: First, you have only one user, so move this:
<span id="userData" data-name="{{ auth()->user()->name }}"
data-surname="{{ auth()->user()->surname }}"></span>
outside of the loop (or put it inside the $loop->first block), so that the #userData id is only assigned once in the DOM.
Next remove the singular id #name from the input. Same for the #surname. The way you have it, it keeps assigning multiple id fields with the same id. The name="participant_name[]" is fine, and will work on POST.
It's not clear if you want the user name & surname to populate ALL the input fields, or just one near the place he checks the box. If you want to populate them all, add a class to the two inputs in the loop like 'firstName' and 'surname'. Then its easy to populate everything with your jquery:
$('.firstName').val(userData.data('name'));
$('.surname').val(userData.data('surname'));
If, however, you wish to populate only the one that is checked, it is a little more complex (but not hard). You will need to have a check box within each loop next to the set of inputs. Easiest way to track the right checkbox against the input fields is to add an iterator into the loop (assign it and then iterate: $x ++) and then use this on the checkbox in a data field (eg data-count={{$x}} ) and now add an id onto the inputs like so:
id = 'name{{$x}}'
id = 'surname{{$x}}'
From here, add to your jquery code to check which box was checked by getting the count from the data-count field on the checkbox. Then, you can identify the right inputs to add the User's name into by id:
var count = $(this).data('count');
$('#name'+count).val(userData.data('name'));
$('#surname'+count).val(userData.data('surname'));
Hope this helps

How to update checkbox field and option field in Laravel 5.2?

I can update text field of a form but i can not update checkbox field,option field and file field in Laravel 5.2. I i going to update then i can see all text value is perfectly shown in update blade view but in option field, checkbox field i see it is default value its don't comes from database. Again if i update with another option then its not saving.What i have tried so far:
My Controller:
public function update(Request $request, $id=0)
{
//
$id = $request->input("id");
$product = Product::find($id);
$product->product_name = $request->input('product_name');
$product->product_storage = $request->input('product_storage');
$product->product_percentage = $request->input('product_percentage');
$product->can_draw = $request->input('can_draw');
$product->real_price = $request->input('real_price');
$product->product_image = $request->input('product_image');
$product->save();
$request->session()->flash('alert-info', 'Product Successfully Updated!');
return Redirect::to('admin/product/all');
}
My update.blade.php View:
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('common.can_be_draw') }}</label>
<div class="col-md-9">
<div class="input-icon">
<i class="fa fa-money" aria-hidden="true"></i>
<select name="can_draw" class="form-control">
<option value="{{ $product->can_draw }}">{{ trans('common.open') }}open</option>
<option value="{{ $product->can_draw }}">{{ trans('common.close') }}close</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('common.real_prize') }}</label>
<div class="col-md-9">
<div class="input-icon">
<input type="radio" class="form-control" name="real_price" value="{{ $product->real_price }}"> {{ trans('common.yes') }}yes
<input type="radio" class="form-control" name="real_price" value="{{ $product->real_price }}" checked="checked"> {{ trans('common.no') }}no
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-md-3 control-label">{{ trans('common.product_picture') }}</label>
<div class="col-md-9">
<input type="file" id="exampleInputFile" name="product_image" value="{{ $product->product_image }}">
<small>{{ trans('common.pic_summery') }}</small>
</div>
</div>
Just use this:
<input type="radio" {{$product->can_draw == 'Yes' ? 'checked' : ''}} class="form-control" name="real_price" value="Yes"> {{ trans('common.yes') }}yes
<input type="radio" {{$product->can_draw == 'Yes' ? '' : 'checked'}} class="form-control" name="real_price" value="No" > {{ trans('common.no') }}no
EDIT
I have edited the above*
You should change the value to Yes and No and use this to check if the value saved is Yes or No. It does not matter how much is real_price
your option field have same value ({{ $product->can_draw }})
<option value="value1"{{( $product->can_draw=='value1'?selected)}}>{{ trans('common.open') }}open</option>
<option value="value2 " {{( $product->can_draw=='value1'?selected)}}>{{ trans('common.close') }}close</option>
and for file field must use file not input:
$product->product_image = $request->file('product_image');
You just can save option value by requesting from select name.
In your example:
select name = "can_draw"
Just save value from request:
$product->can_draw = $request->can_draw;
For checkbox same:
$product->real_price = $request->real_price;
Not necessary indicate input() helper in request.
To retrieve all value for option and check box value, please use foreach methods:
#foreach($can_draws as $can_draw)
<option value="{{ $can_draw->id }}">{{ $can_draw->name}}</option>
#endforeach

Categories