Trying to get value of checkbox from form to controller - php

I'm trying to do something that allows me to upload photos when I check a checkbox control. I got the client side working correctly such that when the checkbox is checked the upload controls are displayed and the form validates correctly.
However, in my controller I need to take some action if my checkbox was checked (true) calling a certain method. If it isn't checked (false) I perform some other action.
In my html page I have the following:
<form action="/supplier/submit/plan" method="post" role="form" id="plan-form">
...
<input name="checkingPhotos" type="checkbox" id="chkPhotos" />
<label for="chkPhotos">I want to include photos in this plan.</label>
...
</form>
However, in my controller I just want to for now see if I get the correct value in my checkbox. For this I did something simple as:
public function submitPlan(Request $request)
{
$checkboxValue = $request->input('checkingPhotos');
dd($checkboxValue);
}
The result is null is printed whether I check the checkbox or not. My route also looks like this:
Route::post('/submit/plan', 'SupplierController#submitPlan');
Can someone please tell me what I am doing wrong here? I just want to see the value 1 / True or 0 / False in my controller method.

Value
The real issue is that you don't have a value for your check box. Add a value, and your problem is solved. It should be:
<input name="checkingPhotos" type="checkbox" id="chkPhotos" value="1" />
[] creates an array
The answer Dylan Kas submitted about changeing the name to add [] works, but not for the reasons you think. Lets take a look:
<input name="checkingPhotos[]" type="checkbox" id="chkPhotos" />
Will pass in the post string:
checkingPhotos[]=On
Which, in PHP will automatically be turned into an array.
Refernce Frame Challenege
Why do you have a checkbox in the first place? Is the checkbox needed? Why not just check for the existence of the file.
$validated = $request->validate([
//... other fields here.
'image' => 'mime:png,gif,jpeg|max:10000' //set max to file size limit you want
]);
$plan = new SupplierPlan($validated);
if($request->has('image')){
$plan->image = $request->image->store();
}
$plan->save();
// ... flash message, return view or redirect

If it's a checkbox you should modify the name of your input to
<input name="checkingPhotos[]" type="checkbox" id="chkPhotos" />
Then you should be able to get the value as you want it with
$request->input('checkingPhotos');

It seems your problem is in your route, change it to
Route::post('/supplier/submit/plan', 'SupplierController#submitPlan');

Related

Laravel 5 : Why is my request->input returning null

I'm trying to return the value of a checkbox within my laravel controller, but every time I request a input from a checkbox element in a form, it returns null.
My controller, retrieving the input of a element called Filter-Method.
Here I'm trying to request a input method called filter-method which is a checkbox.
My Route, since this function will execute on a button:
My Blade, where I'm trying to retrieve the result of my filter-method checkbox:
On line 38 I have a checkbox called filter-method, and when you click on the button on line 115 it should send a request to the controller where it would return a result but instead it returns null
Any ideas of why I'm returning null?
You are not passing any parameter named filter-method. If you are posting values you should use post method.
Like following
Route::post('GetFilterByColumns','MentorController#FilterByValuesColoumns')
If you want to list data according to filter-method then try the following.
Route::get('GetFilterByColumns/{filter-method}','MentorController#FilterByValuesColoumns')
And in your mentorlist.blade.php page
change the href value according to route.
You have to add form to your blade around checkbox either with get or post method as per your requirement change route according to your form method
consider demo blade file
<form method="get" action="{{ url('GetFilterByColumns') }}" class="form-horizontal form-label-left" id="">
<div class="checkbox">
<label><input type="checkbox" name="filter-method" value="filter-method>Method</label>
</div>
<input type="submit" value="submit"/>
</form>
Now you will get a checkbox value in contoller
This is very basic thing just use form instead of <a> tag. Every time you need to send input value to server you need to use <form> element. In image you have uploaded there is no <form> and you are using a <a> tag.
You need to do it like this
<form method="get" action="/getFilterBycolumns">
<input type="checkbox" name="filter-method">
// other input fields
// and then a submit button instead of <a>
<button class="your-class" type="submit"> Send</button>
just use POST instead of GET if you are sending form values

Setting checkbox to checked using PHP is results in no way to clear the checked attribute after render

I have a checkbox in my form which looks like this:
<input class="form-control" type="checkbox" id="showCTA" name="showCTA" <?php echo $block['showCTA'] ? 'checked' : ''; ?> />
Everything works fine with this mark up....unless the PHP value equals 1(already checked). If this is the case, I can check and uncheck the box in the from end visually, but the actual html attribute does not change resulting in the same value of 1 being saved to my database on submit.
How can I work around this in a clean manner? I assume the issue is since the PHP value is absolute until submitted, it means the condition around my "checked" attribute is also absolute, therefore I cannot change the attribute.
If the checkbox is not checked and you post the form, the $_POST['showCTA'] will be undefined. So you should use the isset($_POST['showCTA']) method which will return true if the checkbox is checked and if not, false.

Passing checkbox state to PHP

<input type="hidden" name="check_box_1" value="0" />
<input type="checkbox" name="check_box_1" value="1" />
This works fine, however when you click on submit, and the checkbox is ticked, it passes BOTH the hidden value and the original checkbox value to the $_POST variable in php, can this be avoided?
I have the hidden value there, so that unticked checkboxes are passed to the $_POST variable as well as the ticked ones.
The better approach is to remove the hidden field, and simply have a check in PHP:
if ($_POST['check_box_1']=='1') { /*Do something for ticked*/ }
else { /*Do something for unticked*/ }
You shouldn't need the hidden field. You should in fact not trust any of the form fields sent in the first place. What this means is that you cannot make code which takes the sent fields and trust them to send the correct data (which I assume you do now).
What you should do is to handle all fields you expect to get. That way if you don't get the checkbox value you can still handle that as if it was unticked. Then you also get the added inherent feature of throwing away form data you don't expect in the first place.
No, it will pass all the form data, whatever it is. The right way to do this is not to set the checkbox via a hidden field but to set the checkbox with whatever its state actually is!
I mean... why are you adding the hidden field to begin with?
Your PHP is receiving two fields named check_box_1, and last time I checked there was no way to guarantee that the params would get read into the REQUEST hash in the exact same order as you sent them, so, there's no way to tell which one will arrive last (that's the one whose value will get set). So... this is not the right approach to whatever problem you're trying to solve here.
Welcome to Stack, btw! If you find answers useful or helpful, make sure to mark them as correct and vote them up.
That's normal.
They must be both type="checkbox" to pass only 1 value.
If you want to get only 1 in any cases you can do:
<input type="checkbox" style="display:none;" name="check_box_1" value="0">
Make sure the first input field is of type Checkbox, or else it won't behave like one.
<input type="checkbox" name="check_box_0" value="0" />
<input type="checkbox" name="check_box_1" value="1" />
Everything is working normal with your code so far.
I'm assuming you are creating the hidden field so that 0 is passed to the server when the checkbox is not checked. The problem is that they both get passed when the check box is checked.
As Death said, the way you should be doing it is with a single checkbox and then checking if the value has been sent to the server or not. That's just how checkboxes work.
If you want to have a default set then you will have to handle all that on the server side based on weather the checkbox has a value.
For example:
$myValue = "";
if(isset($_POST['check_box_1']))
{
$myValue=$_POST['check_box_1'];
}
else
{
$myValue="0";
}

Update MySQL DB with PHP from Checkbox

I am pulling data down from a MySQL table and loading it into a form for editing(updating) a record. Everything is working great until I come the the check boxes. The checkboxes in the form accurately reflect the values in the appropriate columns in the db. But when the person editing changes the checkbox in the edit form it does not pass the data to the database. I have read a ton of checkbox Q&A on stack overflow but don't seem to find what I am looking for. Sorry if this is a redundant Question. Here is the code.
<label for="amenities-beach">
<input class="choose" name="amenitiesB" id="amenities-beach" type="checkbox"
value="<?php echo $row1["amenitiesB"]; ?>"
<?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
Close to Beach</label>
Where amenitiesB in:
value="<?php echo $row1["amenitiesB"]; ?>
is what has been returned from the DB with a SELECT statement with:
$row1 = mysql_fetch_array($result);
But when I change the value in the form and submit it nothing is passed to the variable in the UPDATE statement. Any idea what I am missing? I have 6 of these checkboxes,amenitiesB, amenitiesK, amenitiesS, amenitiesP, amenitiesF, and preferred all with the same code. Any help would be appreciated.
Thank You,
Dave
Ok here is the code: Everything else in the form updates fine. I attempt to pass it to:
$amenitiesB = $_POST['amenitiesB'];
then I put it into the update statement
Hotels.amenitiesB='".$amenitiesB."',
My UPDATE statement is,
$query="UPDATE Hotels
JOIN surfcup_Rates ON Hotels.id = surfcup_Rates.hotelid
SET Hotels.hotel='".$hotel."',
More columns, then
Hotels.amenitiesB='".$amenitiesB."',
Hotels.amenitiesB='".$amenitiesK."',
Hotels.amenitiesB='".$amenitiesS."',
Hotels.amenitiesB='".$amenitiesP."',
Hotels.amenitiesB='".$amenitiesF."',
Hotels.amenitiesB='".$preferred."',
More columns then:
WHERE Hotels.id='".$id."'";
The problem you have comes because when a checkbox is unchecked, by default its data is not transmitted to your PHP, and that's why you have problems by having the UPDATE query parameter empty.
So before your update statement you should have:
$fieldenabled=(bool)(isset($_POST['CHECKBOXNAME']) ? TRUE : FALSE;
And call your UPDATE query with that.
EDIT: Of course you can change $_POST with $_GET depending on the sending method of the <form>
Edit: I think I get the problem. When the box is initially unchecked, the input has an empty value, then when you check it, it passes an empty value in... it will never fill with what you intend the checked value to be. So, instead you need something like this:
<input class="choose" name="amenitiesB" id="amenities-beach" type="checkbox" value="amenity B Selected" <?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
... don't make the "value" attribute dynamic, or else once it becomes empty it will always be empty.
Original Answer:
I assume when you say "change the value in the form" you mean that you uncheck the checkbox... unchecked checkboxes never send any data when you submit the form. You check for "unchecked" status by checking to see if the form variable has been passed at all.
For example:
if (isset($_GET['amenitiesB'])) {
// process with the knowledge that "amenitiesB" was checked
}
else {
// process with the knowledge that "amenitiesB" was unchecked
}
If you mean that you somehow dynamically change the "value" of the checkbox to something else, then I'll need to see the code that accomplishes that.
The main purpose of the "value" attribute in a checkbox input is when you're passing the variable as an array:
<label for="amenities-beach">
<input class="choose" name="amenities[]" id="amenities-beach" type="checkbox" value="<?php echo $row1["amenitiesB"]; ?>" <?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
Close to Beach
</label>
... note specifically that I've changed the "name" attribute from "amenitiesB" to "amenities[]", which, if carried through all of your amenities checkboxes, will give you access to them all in your processing script through the $_GET['amenities'] array (or $_POST, if applicable). Otherwise, there's not much reason to use the "value" attribute of the checkbox input, because you can get all you need just by knowing $_GET['amenitiesB'] is checked (and thus sent with the form) or unchecked (and not sent with the form).

Radio button how to?

what i want to do is that when you vote Y or N (two different radio buttons) and then it inserts into the "vote" column(in database) = Y or N(what you pickd), if nothing then echo error.
I know how to do this like halfway, i never worked with radiobuttons before so i need you guys.
Here's a two radio button right:
Yes: <input type="radio" value="Y" id="voteYes" name="vote"></input> <br>
No: <input type="radio" value="N" id="voteNo" name="vote"> </input>
I gave the value N and Y, not the same ID, but the same name. I think its right, but how should i do with the PHP part of what i want to do? I mean shall i call for "vote"? ($_GET["vote"]) i dont think so.. here's where im stuck
You're almost there. Depending on whether or not your form uses the GET or POST method, you'll have to change the variable name appropriately.
if(isset($_GET["vote"])) //checks to see if the user inputed something
{
$value = $_GET["vote"]; //remember, this value is not guaranteed to be either Y or N
}
else
{
//display your error
}
Why not? Just make sure you validate your data... make sure $_GET['vote'] must be an element of array('Y', 'N'), if true you insert it, else echo error and you're done.
POST variables are found in $_POST.
echo $_POST['vote'];
It depends on the method used. If you POST the form, then the variable will be $_POST['vote'], if you GET the form (default) then it will be $_GET['vote'].
Specify the method used in the form tag:
<form action="foo.php" method="POST">
or...
<form action="foo.php" method="GET">
Check for the existance of the variable either with isset() or array_key_exists().

Categories