I have a few checkboxes that are stored as 0 for unchecked or 1 for checked as booleans.
I am now trying to echo back the values using laravel such as
echo $request->facebook
Which returns 1 or 0. It does not return the value of "facebook".
In my view I have:
<input type="checkbox" value="facebook" name="facebook" class="css-checkbox" />
In my model I have this:
$request->facebook = Input::has('facebook');
$request->save();
The model will check the form for the checkbox facebook and saves the boolean value in the database.
What is the best way to echo "facebook" if the checkbox was checked or echo out nothing, if the checkbox was unchecked?
This is what I do for checkboxes in my controllers:
$object = new MyObject;
$object->facebook = Input::has('facebook') ? 1 : 0;
$object->twitter = Input::has('twitter') ? 1 : 0;
$object->somethingElse = Input::has('someCheckbox') ? 1 : 0;
$object->save();
There may be better ways to do it but this is what I typically do. It's easy to read and understand and keeps your code organized.
I've experimented with moving things like this into the model using mutators, but I was kind of unsure about using the Input class on the model. In your controller POST method, the Input class is always going to be there. There is always going to be Input to check and use. But on some random model method, it's possible that you may access that method someday outside of a POST request and then there is no post input, so things like Input::has() will return false and set those values to zero.
There may be a more elegant way to do it. I'm not sure what though.
Related
So, I'm running this code
<td><input type="checkbox" name="bill[]" <?php if ($row['BillBack'] === '1') echo "checked"; ?>></td>
which creates a check box each time
while ($row1 = $result1->fetch_assoc()) {}
runs. So, right now it has 25 entries.
I want on submit button click, if the checkbox is checked to throw 1 into the database, and if it is not, to throw 0. Now, it seems the way to check if an array of check boxes is checked is with
foreach($_POST['bill'] as $selected){
echo $selected."</br>";
}
which, will return "on" for each one that is selected. BUT, my SQL has to look something like
"UPDATE Requests SET BillBack = '$bill' WHERE RequestID = $row['RequestID']"
so I assumed I needed to put the foreach loop inside of the while loop. But that returns 576 "on's"
Throwing an
(!isset($_POST['bill']))
into the while loop doesn't work, as it seems to be toggled if any of them are set, even though removing the ! only returns 24 "on's" (there is only one that is not toggled). so is there a way that while I still have the $row['RequestID'] to be able to check if each check box is set or not, and then throw it into my table while it is still associated with a $row?
Add the $row["requestID"] as the value of the checkbox. Then your bill[] will contain the requestID's you need.
For checkboxes, the contents of the value property do not appear in the user interface. The value property only has meaning when submitting a form. If a checkbox is in checked state when the form is submitted, the name of the checkbox is sent along with the value of the value property (if the checkbox is not checked, no information is sent).
IOW, all those unchecked checkboxes send nothing, so if only two are checked you will only have two items in your array. Without a value, determining which two is impossible.
foreach ($bill as $id) {
UPDATE Requests SET BillBack = '1' WHERE RequestID = $id;
}
And you can optimize that sql using "in" but I'm at work and don't have time
I am using checkboxes in my form to allow the user to turn on/off certain settings. I load the form by providing the correct 'state' from values returned from the db. They can then change these and submit the form where it is processed. Example...
<input type="checkbox" name="settings[something]" '.($settings[one] == 1 ? 'value="1" checked' : 'unchecked').'/>
<input type="checkbox" name="settings[somethingelse]" '.($settings[one] == 1 ? 'value="1" checked' : 'unchecked').'/>
... and so on...
On the receiving end is where I can't seem to come up with a good solution to handle these.
If any of these are unchecked then the value is not even sent. If it is checked then a value of '1'.
So, other than doing something like :
$something = $_POST['settings'][something']
$somethingelse = $_POST['settings'][somethingelse']
... and so on
if (!$something == 1)
{
$something = null;
}
... and so on
for each value I am expecting... is there an easier way I am missing here? I have to check each value whether it was sent or not because I am also including an option to set these values as default for multiple rows in my db - not just the one they are editing.
EDIT :
I took some time to think about this. In my database I am storing these as 1 or 0 values. Rather than checking if they were posted (set) on the receiving end of the form I am going to check if they are != to 1. I can run down the list of values and everything that is not equal to 1 is set to 0. This way I have a full list of all values to update in the db AND I am verifying the data integrity before inserting it into the database (1 or 0).
I am now trying to think of a quicker way to run through my 'list' to check rather than an if statement for each. Going to play around with some arrays and see what I can come up with.
Checkboxes are a bit special as they are not sent to the server when they are not checked.
So the best way to check for a checkbox, is not by it's value, but simply by checking if it is set:
if (isset($_POST['settings']['something']))
{
// Do what you need to do
}
else
{
// The checkbox was not on the form (you should know that already) OR unchecked
}
On my website, I have user accounts that are configurable with forms that allow users to update everything from first and last names to privacy settings. I use the following function to update the database with that input. (Note that the following code uses WordPress-specific features.)
function update_account() {
global $current_user; get_currentuserinfo();
require_once( ABSPATH . WPINC . '/registration.php' );
$uid = $current_user->ID;
// First Name
if(isset($_POST['first_name']) && $_POST['first_name'] <> $current_user->first_name) {
wp_update_user( array(
'ID' => $uid, 'first_name' => esc_attr($_POST['first_name'])
));
}
// ...and so on 43 more times...
}
This feels like the wrong way to process forms. This also looks like it will negatively impact server performance when there are multiple users and frequent updates, given that the if-then-else conditions for every field, even fields not on a particular page, force checking each field for input.
Moreover, since form data can be expected to remain relatively constant, I added the <> operator to prevent the function from updating fields where there has not been any change, but I suspect this also means that every field is still evaluated for change. To make matters worse, adding new fields -- there are already 44 fields in total -- is an unwieldy process.
What's a better way to process form data?
Keep an array of the fields you will be processing with this code, and iterate over it. This works if all your attributes are strings, for example. If you have different data types such as boolean flags to handle differently from the strings, you may wish to group them into their own array.
// All the fields you wish to process are in this array
$fields = array('first_name', 'last_name', 'others',...'others99');
// Loop over the array and process each field with the same block
foreach ($fields as $field) {
if(isset($_POST[$field]) && $_POST[$field] != $current_user->{$field}) {
wp_update_user( array(
'ID' => $uid, $field => esc_attr($_POST[$field])
));
}
}
There's a lot of things missing with your implementation. I don't know what kinds of data you're allowing the user to manipulate but most usually have some kind of requirements to be acceptable. Like not having certain characters, not being blank, etc. I don't see any validation occurring, so how do you handle values that might be undesirable? And what happens when you receive bad data? How do you inform the user of the bad data and prompt them to correct it?
If we abstract the situation a bit we can come up with generalizations and implement an appropriate solution.
Basically form fields [can] have a default value, a user specified value [on form review], validation requirements and validation errors [with messages]. A form is a collection of fields that upon form submit needs to be validated and if invalid, re-displayed to the user with instructive corrective prompts.
If we create a form class that encapsulates the above logic we can instantiate and use it to pass around our controller/views. Oops, I was just assuming you were using an Model/View/Controller type framework, and I'm not really familiar with wordPress so I don't know if that is exactly applicable. But the principle still applies. On the page where you both display or process the form, here's some pseudo logic how how it might look.
function update_account()
{
// initialize a new form class
$form = new UserAccountInfoForm();
// give the form to your view for rendering
$this->view->form = $form;
// check if form was posted [however your framework provides this check]
if(!Is_Post())
return $this->render('accountform.phtml');
// check if posted form data validates
if(!$form->isValid($_POST))
{
// if the form didn't validate re-display the form
// the view takes care of displaying errors, with the help of its
// copy of the $form object
return $this->render('accountform.phtml');
}
// form validated, so we can use the supplied values and update the db
$values = $form->getValues(); // returns an array of ['fieldname'=>'value']
// escape the values of the array
EscapeArrayValues($values);
// update db
wp_update_user($values);
// inform the user of successful update via flash message
$this->flashMessage('Successfully updated profile');
// go back to main profile page
$this->redirect('/profile');
That makes your controller relatively clean an easy to work with. The view gets some love and care to, utilizing the $form value to display the form correctly. Technically, you can implement a method in the form class to give you the form html, but for simplicity I'm just going to assume your form html is manually coded in accountform.phtml and it just uses $form to get field info
<form action='post'>
<label>first name</label> <input class='<?=$this->form->getElement('first_name')->hasError() ? "invalid":""?>' type='text' name='first_name' value="<?=$this->form->getElement('first_name')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('first_name')->getError()?></span><br/>
<label>last name</label> <input class='<?=$this->form->getElement('last_name')->hasError() ? "invalid":""?>' type='text' name='last_name' value="<?=$this->form->getElement('last_name')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('last_name')->getError()?></span><br/>
<label>other</label> <input class='<?=$this->form->getElement('other')->hasError() ? "invalid":""?>' type='text' name='other' value="<?=$this->form->getElement('other')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('other')->getError()?></span><br/>
<input type='submit' value='submit'/>
</form>
Here the pseudo code relies on the form class method "getElement" which returns the field class instance for the specified field name (which would be created an initialized in the constructor of your form class). Then on the field class methods "hasError" and "getError" to check if the field validated correctly. If the form has not be submitted yet, then these return false and blank, but if the form was posted and invalid, then they will have been set appropriately in the validate method when it was called. Also "getValue" would return either the value supplied by the user when the form was submitted, or if the form has not been submitted, the default value as specified when the field class was instantiated and initialized.
Obviously this pseudo code is relying on a lot of magic that you'd have to implement if you roll your own solution--and it's certainly doable. However, at this point I'll direct you to the Zend Framework Zend_Form components. You can use zend framework components by themselves without having to utilize the entire framework and application structure too. You might also find similar form component solutions from other frameworks but I wouldn't know about those (we are a Zend Framework shop at my work place).
Hopefully this hasn't been too complicated, and you know where to go from here. Of course just ask if you need any clarification.
I'm using the CodeIgniter framework.
I'm using the form_input function to make a 2d array of textboxes and pulldowns.
The function produces HTML like this:
<input type="box" name= "variable">
I need to create 30 rows of 5 textboxes (time, event, supplies, sucess{yes/no}, comment).
My plan was to somehow be able to uniquely identify them all so at a later stage when I $Post them to another page it wont get confused as to which textbox is time1 or which textbox is time2.
I'm trying to make this array of texboxes in php so that when I use a for loop with (ISSET) I can stop when I get to a row that is not completed by the user.
This is my code here but im not too sure if its spot on
for ($i =0; $i< 30; $i++)
{
//time part of event field
echo form_input ($events['time',$i]),
//the event itself
form_input ($events['event',$i]),
//supplies used
form_input ($events['supplies',$i]),
//successful?
form_dropdown ($events['success',$i] $success),
//comment if necessary
form_input ($events['time',$i]);
echo '<br/>';
}
I really don't understand either but regarding the $_POST object; this is from the CI docs:
CodeIgniter comes with three helper
functions that let you fetch POST,
COOKIE or SERVER items. The main
advantage of using the provided
functions rather than fetching an item
directly ($_POST['something']) is that
the functions will check to see if the
item is set and return false (boolean)
if not. This lets you conveniently use
data without having to test whether an
item exists first. In other words,
normally you might do something like
this:
if ( ! isset($_POST['something']))
{
$something = FALSE;
}
else
{
$something = $_POST['something'];
}
With CodeIgniter's built in functions
you can simply do this:
$something = $this->input->post('something');
I know result page that uses GET method can be bookmarked while the one using POST cannot be. I also know about the restrictions of the GET methods.
Now suppose I want to build a search engine which by default uses GET allowing users to bookmark but when the length of the search phrase exceeds the limit, switch to POST. On the server side I make use of $_GET or $_POST depending on which is set.
Is this doable?
If no, why?
If yes, please provide a brief outline.
Thanks
It is doable, no problem.
There is the $_REQUEST array that merges GET, POST, and COOKIE values but the better way would be to handle GET and POST manually in your script.
Just have your engine check both $_GET["variable"] and $_POST["variable"] and use whichever is set. If a variable is set in both methods, you need to decide which one you want to give precedence.
The only notable difference between the two methods is that a GET parameter has size limitations depending on browser and receiving web server (POST has limitations too, but they are usually in the range of several megabytes).
I think the general rule is that a GET string should never exceed 1024 characters.
Here's how you could use GET and POST in one:
<form action="myfile.php?var1=get1&var2=get2&var3=get3" method="post">
<input type="hidden" name="var1" value="post1" />
<input type="hidden" name="var2" value="post2" />
<input type="submit" />
</form>
The PHP:
print_r($_REQUEST);
// var1 = "post1"
// var2 = "post2"
// var3 = "get3"
print_r($_GET)
// var1 = "get1"
// var2 = "get2"
// var3 = "get3"
print_r($_POST);
// var1 = "post1"
// var2 = "post2"
You could use something like the following:
<?php
function getParam($key)
{
switch (true) {
case isset($_GET[$key]):
return $_GET[$key];
case isset($_POST[$key]):
return $_POST[$key];
case isset($_COOKIE[$key]):
return $_COOKIE[$key];
case isset($_SERVER[$key]):
return $_SERVER[$key];
case isset($_ENV[$key]):
return $_ENV[$key];
default:
return null;
}
}
It's also as well to be aware that using GET opens up a temptation among certain sets of users to manipulate the URL to 'see what happens' so it's absolutely necessary to ensure that your code suitably sanitises the input variables.
Of course you were doing that anyway ;-). But with get it pays to be doubly paranoid.
Myself if I'm using GET I'll generally set a cookie too and drop an ID of some sort in it, then cross-correlate that to a variable in the GET list, just to make sure there's absolutely no issues over user A manipulating the input and letting them see anything originating with user B.
Yes its doable, although (IMHO) the limit at which GET becomes cumbersome is significantly greater than the threshold at which a user interface for providing this much information becomes unusable. Also, the more complex a query you submit to a conventional search engine, the more effectively it can be resolved.
But I'm guessing you have your reasons.
The simplest way, from the information you've provided, to achieve this would be to change the form method at run time from GET to POST using javascript, e.g.
<form method='GET' id='searchform' target='search.php' onsubmit='
if (document.getElementById("searchdata")) {
if ((document.getElementById("searchdata").length >$some_threshold)
&& (document.getElementById("searchform"))) {
// 2nd if in case this moved to action for button
document.getElementById("searchform").method="POST";
}
}
return true;'>
<textarea name='searchdata' id='searchdata'>
</textarea>
<input type='submit' value='go get it'>
</form>
Which also downgrades nicely for non-javascript clients.
C.
function getQVar($key){
return isset($_GET[$key]) ? $_GET[$key] : (isset($_POST[$key]) ? $_POST[$key] : null);
}
echo getQVar("name");
Switch around $_GET and $_POST to prioritize POST over GET vars.