how to save checkbox with multiple value in laravel 5.5 - php

i'm having difficulty saving multiple item using checkbox, with this code i can only save one value at a time..can anyone give me idea
Controller:
$crud = explode(',', $request->crud_selected);
if (count($crud) > 0) {
foreach ($crud as $x) {
$slug = strtolower($x) . '-' . strtolower($request->resource);
$display_name = ucwords($x . " " . $request->resource);
$description = "Allows a user to " . strtoupper($x) . ' a ' . ucwords($request->resource);
$permission = new Permission();
$permission->name = $slug;
$permission->display_name = $display_name;
$permission->description = $description;
$permission->save();
}
Session::flash('success', 'Permissions were all successfully added');
return redirect()->route('permissions.index');
}
} else {
return redirect()->route('permissions.create')->withInput();
}
View-blade:
<script>
var app = new Vue({
el: '#app',
data() {
return:{
permissionType: 'basic',
resource: '',
crudSelected: []
}
}
});
</script>
<div class="from-group" v-if="permissionType == 'crud'">
<div class="checkbox-group" v-model="crudSelected">
<label class="checkbox-inline"><input type="checkbox" name="crud_selected" value="create">Create</label>
<label class="checkbox-inline"><input type="checkbox" name="crud_selected" value="read">Read</label>
<label class="checkbox-inline"><input type="checkbox" name="crud_selected" value="message">Update</label>
<label class="checkbox-inline"><input type="checkbox" name="crud_selected" value="message">Delete</label>
</div>
</div>
Any idea how to fix this.

I already manage to find answer this is what do i change the controller code.
Old
$crud = explode(',', $request->crud_selected);
New
$crud = $request->input('crud_selected');
then on my view-blade i add this to my
name="crud_selected[]
Wallahh it works..

if you want to take more than checked value on checkbox inputs, i think you can do it by define a function will call on each change event on your check box for example like this
<label class="checkbox-inline"><input type="checkbox" id ="checklval" name="crud_selected" v-model="crudSelected" v-on:change="trackcheck(Create)" :value="Create" >Create</label>
then on your vue component script you will implement this function,
i define array called ValArray will pushed on it each value selected on check box and will also pop from it if this value not checked on check box like this below :
trackcheck($labid) {
if(document.getElementById('checklval').checked==true){
this.ValArray.push($labid)
} else if(document.getElementById('checklval' ).checked==false){
this.ValArray.pop($labid)
}
}
now you will have an array with each selected value on check box inputs,
hope this help you

You don't need explode value, because the checkbox values returns array.
v-model is only used in input.
Form Input Bindings
<div class="from-group" v-if="permissionType == 'crud'">
<div class="checkbox-group" >
<label class="checkbox-inline"><input type="checkbox" v-model="crudSelected">Create</label>
<label class="checkbox-inline"><input type="checkbox" v-model="crudSelected">Read</label>
<label class="checkbox-inline"><input type="checkbox" v-model="crudSelected">Update</label>
<label class="checkbox-inline"><input type="checkbox" v-model="crudSelected">Delete</label>
</div>
</div>

Related

Saving multiple checkbox value and different input value into database as one

I'm trying to insert a data/value into my database.
It works but the problem is that every time I select the second value/checkbox only its other input value gets the value of the first input.
<form action="{{url('/reservation')}}" method="post">
#csrf
<div class="row col-12">
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="JasminBooks"/>JasminBooks</p>
</div>
<div>
<input type="number" name="prod_qty[]" min="1" value="1"class="form-control ml-2">
</div>
<div class="row col-12">
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="KnowHowBooks"/>KnowHowBooks</p>
</div>
<div>
<input type="number" name="prod_qty[]" min="1" value="1"class="form-control ml-2">
</div>
</div>
</form>
This is the code for my controller function
public function reservation(Request $request)
{
$data = new reservation;
$data->name = $request->name;
$data->email = $request->email;
$data->phone = $request->phone;
$data->address = $request->address;
$data->date = $request->date;
$data->time = $request->time;
$products = null;
$checked_array = $_POST['prod_name'];
foreach($_POST['prod_name'] as $key => $value) {
if (in_array($_POST['prod_name'][$key], $checked_array)) {
$products .= $_POST['prod_qty'][$key]." ".$_POST['prod_name'][$key].", ";
}
}
$data->products = $products;
$data->save();
return redirect()->back();
}
The result and the data is saved into the database when
I select the first checkbox and input a value of quantity 5 the result is "5 JasminBooks,"
When I select both checkboxes and input a value of quantity 12 in the first input beside the first checkbox and 7 for the second input/quantity besides the second checkbox the result is "12 JasminBooks, 7 KnowHowBooks, "
But when I only select the second checkbox and input a value of 13 for the quantity the result is "1 KnowHowBooks, " it takes the default value of the first input rather than the second input where I inserted 13 as the quantity.
What should I add/change in my code?
It's because you're defining your quantity fields based on index. If a single input is missing, it could throw off your whole result. Use the value as key:
HTML:
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="JasminBooks"/>JasminBooks
</p></div><div>
<input type="number" name="prod_qty[JasminBooks]" min="1" value="1"class="form-control ml-2">
</div>
PHP:
$products = '';
$checked_array = $request->input('prod_name', []);
$quantities = $request->input('prod_qty', []);
foreach ($checked_array as $value) {
if (array_key_exists($value, $quantities)) {
$products .= "{$quantities[$value]} {$value}, ";
}
}
// Remove trailing ', '
if (! empty($products)) {
$products = substr($products, 0, -2);
}
$data->products = $products;
P.S. Like Bhaumik said, don't use $_POST in Laravel.

How to retain multiple checkbox even page refreshes reset after form submit

i have a form of multiple checkboxes. but i want to retain the checkbox checked but reset it after form submit. here is my code.
<?php
if(isset($_POST['query'])){
$searched = $_POST['query'];
$conn = mysqli_connect('localhost','root','','orderqueing') or die (mysqli_error());
$query = "SELECT * FROM product_tbl WHERE itemName LIKE '%$searched%'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo '<label style="float:left" class="option_item">
<input type="checkbox" id="mycheckbox" class="checkbox" name="prodid[]" value="'.$row['itemName'].'">
<div class="option_inner facebook">
<div class="tickmark"></div>
<div class="icon">'.$row['itemName'].'<input type="hidden" name="prodname[]" value="'.$row['itemName'].'"></div>
<div class="icon">'.$row['itemPrice'].' PHP<input type="hidden" name="price[]" value="'.$row['itemPrice'].'"></div>
<div class="icon"><input type="number" name="multiple[]" style="padding:5px;width:60px;" value="1" ></div>
</div>
</label>';
}
} else {
$conn = mysqli_connect('localhost','root','','orderqueing') or die (mysqli_error());
$query = "SELECT * FROM product_tbl";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo '<label style="float:left" class="option_item">
<input type="checkbox" id="mycheckbox" class="checkbox" name="prodid[]" value="'.$row['itemName'].'">
<div class="option_inner facebook">
<div class="tickmark"></div>
<div class="icon">'.$row['itemName'].'<input type="hidden" name="prodname[]" value="'.$row['itemName'].'"></div>
<div class="icon">'.$row['itemPrice'].' PHP<input type="hidden" name="price[]" value="'.$row['itemPrice'].'"></div>
<div class="icon"><input type="number" name="multiple[]" style="padding:5px;width:60px;" value="1" ></div>
</div>
</label>';
}
}
?>
this is my UI :
enter image description here
because the checked checkboxes resets when i search an item.
i want to retain it checked before the form submits.
i could not think of a solution to this problem. thanks for the help
You can consider recording the checkbox you selected in the cookie when submitting or at the end of the keyup function; then get the cookie in window.onload or your code and give the corresponding checkbox a selected state
I'm not quite sure if you are requesting this data via ajax.This is untested code, but provides an idea; you may need to modify or even use
I thought of the following workaround:
window.onload=function(){
//Called after initialization or search. Check the checkbox
function reloadCheckBox(){
let allProdCheck = document.querySelectorAll("input[name=prodid[]]");
allProdCheck.forEach(element => {
let cooki = getCookie("prod_"+element.value);
if(cooki!=''&&Boolean(cooki)==true){ //if exists (previously selected)
element.checked = true;
}else{
element.checked = false;
}
});
}
}
//Record in cookie when selected
function prodCheck(ele){
setCookie("prod_"+ele.value,ele.checked);
}
function setCookie(cname,cvalue='',exdays=1){
var d = new Date();
//d.setTime(d.getTime()+(exdays*24*60*60*1000));
//var expires = "expires="+d.toGMTString();
//document.cookie = cname+"="+cvalue+"; "+expires;
document.cookie = cname+"="+cvalue;
}
function getCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
}
return "";
}
Then add event onclick="prodCheck(this)" to this statement <input type="checkbox" id="mycheckbox" class="checkbox" name="prodid[]" value="'.$row[' itemName'].'" >
<input type="checkbox" id="mycheckbox" class="checkbox" name="prodid[]" value="'.$row['itemName'].'" onclick="prodCheck(this)" >
you saied cant figure it out on how to use it in multiple checkboxes?http://jsfiddle.net/Lwxoeyyp/1/
<input type="button" id="ReserveerButton1" value="save" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="wis()"/>
<input type="checkbox" id="checkbox1zaal1" onchange="checkChange(this)">1e film van de dag</input>
<input type="checkbox" id="checkbox1zaal2" onchange="checkChange(this)">1e film van de dag</input>
<input type="checkbox" id="checkbox1zaal3" onchange="checkChange(this)">1e film van de dag</input>
function load(){
let checks = JSON.parse(localStorage.getItem('checkbox'));
if(checks!={}){
for(let key in checks){
    document.getElementById(key).checked = checks[key];
   }
}
}
/*one checkbox is checked or unchecked
If you want to use the save method you wrote, you can pass the corresponding single checkbox object as the parameter
*/
function checkChange(ele){
let oldCheck = JSON.parse(localStorage.getItem('checkbox'));
if(oldCheck==null||oldCheck=={}){
oldCheck={};
}
oldCheck[ele.id] = ele.checked;
localStorage.setItem('checkbox', JSON.stringify(oldCheck));
}
load();

Foreach duplicating checkbox inputs form

Instead of having 2 inputs with the full-time and the contractor box ticked, I have 4 inputs see below. How can I avoid the duplication of the inputs, and ends up with two inputs only that will have the boxes ticked for full-time and contractor?
Here is the code:
<?php
$jobEmploymentType = "FULL_TIME,CONTRACTOR";
$jobEmploymentTypeExplode = (explode(",",$jobEmploymentType));
//print_r($jobEmploymentTypeExplode);
foreach ($jobEmploymentTypeExplode as $jobType) : ?>
<span class="asterisk">*</span> <label for="jobEmploymentType">Employment Type</label><br>
<input type="checkbox" class="w3-check" id="fullTime" name="fullTime" value="FULL_TIME" <?= ($jobType == "FULL_TIME")? "checked":"";?>>
<label for="fullTime"> FULL-TIME</label><br>
<input type="checkbox" class="w3-check" id="contractor" name="contractor" value="CONTRACTOR" <?= ($jobType == "CONTRACTOR")? "checked":"";?>>
<label for="contractor"> CONTRACTOR</label><br>
<?php endforeach; ?>
Expecting result:
I've found a way that works for me using in_array:
PHP Code:
$jobTypeExplode = (explode(",",$jobEmploymentType));
if(in_array('FULL_TIME',$jobTypeExplode)) {$fulltime = 'FULL_TIME';}
if (in_array('CONTRACTOR',$jobTypeExplode)) {$contractor = 'CONTRACTOR';}
HTML code:
<input type="checkbox" class="w3-check" id="fullTime" name="fullTime" value="FULL_TIME" <?= ($fulltime == "FULL_TIME")? "checked":"";?>>
<label for="fullTime"> FULL-TIME</label><br>
<input type="checkbox" class="w3-check" id="contractor" name="contractor" value="CONTRACTOR" <?= ($contractor == "CONTRACTOR")? "checked":"";?>>
<label for="contractor"> CONTRACTOR</label><br>
$jobEmploymentType = "FULL_TIME,CONTRACTOR";
Your problem is in the above line. When you give two values to the variable $jobEmploymentType the program is going to spit out the program twice.

Angular - storing checkbox values, and displaying them

Suppose that, you have 27 checkboxes, let's call them 'categories'. These checkboxes are in one section, you can select them multiple, and save.
The eseence is: if you save the form, the categories will be added to your profile, in MySQL.
My question is:
How I should name the models,
How I should store de values after sending the form
I had a solution for this, I saved the nth of the categories, then clicked them back at loading, but that's not the best.
Here is the code:
$scope.getSelectedCats = function() //Returning array: [1,4,5,6]
{
$return_array = [];
$i = 0;
if($scope.whoareu.develop){ $return_array[$i] = 1; $i++;}
if($scope.whoareu.design){ $return_array[$i] = 2; $i++;}
if($scope.whoareu.produce){ $return_array[$i] = 3; $i++;}
if($scope.whoareu.repair){ $return_array[$i] = 4; $i++;}
[...]
return $return_array;
}
HTML
<p>
<input ng-model="whoareu.develop" type="checkbox" value=1 id="WAY8" name="whoareu" />
<label for="WAY8">Develop</label>
</p>
<p>
<input ng-model="whoareu.design" type="checkbox" value=2 id="WAY9" name="whoareu" />
<label for="WAY9">Design</label>
</p>
<p>
<input ng-model="whoareu.produce" type="checkbox" value=3 id="WAY10" name="whoareu" />
<label for="WAY10">Produce</label>
</p>
<p>
<input ng-model="whoareu.repair" type="checkbox" value=4 id="WAY11" name="whoareu" />
<label for="WAY11">Repair</label>
</p>
[...]
And last, a very ugly solution for loading checks:
<?php
//$dbData = Data row from mysql, in object, by Wordpress
echo "setTimeout(function(){";
foreach(explode(',', $dbData->interested_in) as $val)
{
//echo "$('input:checkbox[name=whatareu]').filter('[value=$val]').click();";
echo "$('input:checkbox[name=whatareu]').eq($val-1).click();";
}
echo "}, 1000);";
?>
I don't know if I understand your problem well, see my snippet. If you want, you could create some mapping function setDefaultState(basedOn) which set checked in model checkboxs.
If the problem is that data is lost after you leave the controller, you should use some singleton storage like Angular's factories, and storage the checked categories there.
angular.module('app', [])
.controller('FrameController', ['$injector',
function($injector) {
var vm = this;
vm.checkboxs = [{
id: 'WAY8',
label: 'Develop',
checked: true
}, {
id: 'WAY9',
label: 'Design'
}]
angular.extend(vm, {
save: save
})
function save() {
// API call
console.log('checked: ', vm.checkboxs.filter(function(c) {
return c.checked
}).map(function(c) {
return {
id: c.id
}
}));
}
}
]);
setTimeout(function() {
angular.bootstrap(document.getElementById('body'), ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="body">
<div ng-controller="FrameController as vm">
<ul>
<li ng-repeat="checkbox in vm.checkboxs">
<input ng-model="checkbox.checked" type="checkbox" id="{{checkbox.id}}" name="whoareu" />
<label for="{{checkbox.id}}">{{checkbox.label}}</label>
</li>
</ul>
<button ng-click="vm.save()">
Save
</button>
</div>
</div>

Laravel 4 how do I keep checkbox checked after form is submitted

In part of my edit form I have check boxes. I can submit the form just fine, the values are stored in the database as comma separated values. So apple,microsoft etc. Which works fine but when I go back to the edit form the check boxes are not checked. I tried to echo out checked if the following was met:
<input name="software[]" type="checkbox" value="Ortho trac" <?php if(isset($_POST['software'])) echo "checked"; ?>> Ortho trac
But the above code doesn't work. I am not sure how to do it in laravel. Also when I try to update the values the previous values in the database disappear
The view
<div class="form-group mtop-20">
<label for="temp_software_experience">Software Experience:</label><br>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" class="input-sm" value="Practiceworks"> Practiceworks
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Softdent"> Softdent
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Ortho trac" <?php if (isset($_POST['software'])) echo "checked"; ?>> Ortho trac
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Dentrix"> Dentrix
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Easy Dental"> Easy Dental
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Practiceworks"> Eaglesoft
</label>
<label class="checkbox-inline">
<input type="checkbox" id="temp_software_experience" value="Other"> Other
</label>
</div><!-- end .form-group -->
The Controller
public function update($id)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'firstname' => 'required|min:3|alpha',
'lastname' => 'required|min:3|alpha',
'zipcode' => 'required|min:5|numeric',
'temp_experience' => 'required|min:1|max:50|numeric',
'temp_travel' => 'required|numeric',
'temp_hourly_rate' => 'required|numeric|min:10',
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('user/profile/' . $id . '/edit')
->withErrors($validator)
->withInput();
} else {
$software_checked = Input::get('software');
if(is_array($software_checked))
{
$implade_software = implode(',', $software_checked);
}
// store
$user = User::find($id);
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->zipcode = Input::get('zipcode');
$user->temp_experience = Input::get('temp_experience');
$user->temp_travel = Input::get('temp_travel');
$user->temp_hourly_rate = Input::get('temp_hourly_rate');
$user->temp_software_experience = $implade_software;
$user->save();
// redirect
Session::flash('message', 'Successfully updated profile!!');
return Redirect::to('user/profile/'.$id.'');
}
}
When you update you are redirecting afterwards thus clearing your POST data.
// redirect
Session::flash('message', 'Successfully updated profile!!');
return Redirect::to('user/profile/'.$id.'');
To access this data you will need to fetch it from your method of storage (database in this case), not your POST data as it contains nothing.
So that conditional should be something like:
<?php if(!empty($user->software)) echo "checked"; ?>
Note: You should be using Input::get() even within the view, no point in using $_POST.
Edit from comments:
The reason you are losing the data is because you first need explode() the data before you perform the conditional check against it.
Say you select:
[x] Apple
[ ] Orange
[x] Banana
In your column it would look something like apple,banana.
When you perform a conditional check it looks similar to this:
if ('apple,banana' == 'apple') echo 'checked';
You need to be checking if the an element within that comma delimited list exists. So try exploding it first and then checking it. This should be a good starting point.
$software = explode(',', $user->temp_software_experience);
Then for each input:
if (in_array("Practiceworks", $software)) echo "checked";
Here's the documentation for in_array().
Hope that clears some things up.

Categories