Dynamically Populate Custom Field (Gravity Forms) - php

I've got a form that calculates how many times a person has chosen a value. Each question has 3 answers with a value of either "self", "others", or "social". Whichever has the MOST gets returned as the result.
Ultimately, I need a custom post field hidden from the user, populated with this result. Currently it's being display after form submission with:
return $confirmation
I've got http://pastie.org/3312298 pasted in the bottom of my functions.php file.
I'm not quite sure how to get the result into the box before the form gets submitted to us as an entry.
www.webdesignsalemoregon.com/surveytest
is where it's lying right now

You're taking a way complicated route of doing this.
give each radio button for 'self' <input name='self'>, and do the same for the rest
$self_answers = count($_POST['self']);
$others_answers = count($_POST['others']);
$social_answers = count($_POST['social']);
$max = max($self_answers, $others_answers, $social_answers) ;
if($max == $self_answers) {
$greatest = "self";
} else if($max == $others_answers) {
$greatest = "others";
} else {
$greatest = "social";
}

Related

Check if array of checkboxes are checked from a form (PHP)

I realize this is a question that has been asked before ("Cannot use [] for reading"), but I'm having trouble wrapping my head around the answer and how to fix my particular function.
function check_required_checkbox($checkbox_name, $error, $is_multiple_checkboxes)
{
global $error_msgs;
if ($is_multiple_checkboxes == true)
{
if (!isset($_POST[$checkbox_name][]))
{
$error_msgs[] = $error;
}
else if ($is_multiple_checkboxes == false)
{
if (!isset($_POST[$checkbox_name]))
{
$error_msgs[] = $error;
}
}
}
The problem line is 6, !isset($_POST[$checkbox_name][]), and I'm not understanding how the correct way I should write it. I saw instances of using brackets but !isset($_POST[{$checkbox_name}][]) isn't correct either.
When I have multiple checkboxes that use name="radda[]", I want my function to check that all of the checkboxes with a specific name are checked, and if not, add $error to the $error_msgs[] array.
EDIT:
I discussed with the department that was requesting a rewrite of the old form. Instead of using checkboxes, I switched it to a list of all of the borrower's rights and responsibilities, and then used a radio button below the list to ask the user to select "yes" or "no" on whether they read the list. Then I made it required to select "yes" or "no" and added validation that if "no" was selected, they wouldn't be able to submit the application. This was far easier than trying to make a bunch of checkboxes required. I do appreciate the help that everyone offered though.
If I understood what you need.
Try to define the $checkbox_name variable and then access the POST.
$checkbox_name = 'radda';
if (isset($_POST[$checkbox_name]) && !is_array($_POST[$checkbox_name]))
{
$error_msgs[] = $error;
}
Something like that should work.
Here is a similar thread: Retrieve an associative array value with a variable as key

Basic addition for form security gives wrong answer PHP

I have a basic math question that the user has to answer before they can send an email:
$first_num = rand(1, 4);
$second_num = rand(1, 4);
$send = #$_POST['send'];
if($send){
//The user's answer from the input box
$answer = #$_POST["answer"];
if($answer == $first_num + $second_num) {
//Do stuff
}
else {
$error_message = "You answered the question wrong!";
}
}
I answer the question correctly (unless my first grade math is off!) yet it says I have the question wrong. I am not sure what the issue is but I imagine it is something to do with the fact that php executes immediately when the page is loaded and so new numbers are generated as soon as the user presses the submit button? Or am I way off? If that is the case, what can be done to solve this?
The problem is that you are setting your values every time your script is called. So when you post your form, two new values are set and they are likely not the same values as when you called the script the first time to show the form.
You should store your variables in a session and retrieve these values when you process your post request.
Something like:
session_start();
if (!isset($_SESSION['numbers']))
{
$_SESSION['numbers']['first'] = rand(1, 4);
$_SESSION['numbers']['second'] = rand(1, 4);
}
...
if ($answer == $_SESSION['numbers']['first'] + $_SESSION['numbers']['second']) {
//Do stuff
/**
unset the variables after successfully processing the form so that
you will get new ones next time you open the form
*/
unset($_SESSION['numbers']);
...
Note that you will need to use the session variables everywhere where you are using your own variables right now.
You should include the two numbers as hidden form inputs in your HTML, and then do the math with the entries in your $_POST array.
Make your code start like this instead:
$first_num = $_POST["first_num"];
$second_num = $_POST["second_num"];

Using For loop to get values of multiple elements in PHP

The title is so general mainly because I don't know what should be the appropriate title for it. Let me just explain the situation:
Say that I have two textboxes named LastName0 and FirstName0 and a button called addMore. When I click addMore, another two textboxes will be created through JavaScript. These textboxes will be named LastName1 and FirstName1. When I click the addMore button again, another two textboxes button will be created and named LastName2 and FirstName2 respectively. This will go on as long as the addMore button is clicked. Also, a button named deleteThis will be created alongside the textboxes. This simply deletes the created textboxes when clicked.
I also initialized a variable called counter. Every time the addMore button is clicked, the counter goes up by 1, and whenever the deleteThis button is clicked, the counter decreases by 1. The value of the counter is stored in a hidden input type.
When the user submits the form, I get the value of the counter and create a For loop to get all the values of the textboxes in the form. Here is the sample code:
//Suppose that the user decides to add 2 more textboxes. Now we have the following:
// LastName0 FirstName0
// LastName1 FirstName1
// LastName2 FirstName2
$ctr = $_POST['counter']; //the counter == 3
for ($x = 0; $x < $ctr; $ctr++)
{
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//This will get the values of LastName0,1,2 and FirstName0,1,2
//code to save to database…
}
On the code above, if the value of counter is equal to 3, then the values of textboxes LastName0,1,2 and FirstName0,1,2 will be saved. Now here is the problem: If the user decided to delete LastName1 and FirstName1, the For loop will not be able to iterate properly:
$ctr = $_POST['counter']; //the counter == 2
for ($x = 0; $x < $ctr; $ctr++)
{
//Only LastName0 and FirstName0 will be saved.
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
Someone told me to use the "push and pop" concept to solve this problem, but I am not really sure on how to apply it here. So if anyone can tell me how to apply it, it'll be grand.
Add your input text boxes with name as array ie, <input type="text" name="FirstName[]" />
In php you can fetch them as a array. ie,
foreach($_POST["FirstName"] as $k=>$val){
echo $val; // give you first name
echo $_POST["LastName"][$k]; // will give you last ame
}
In this case even if one set of field is removed in HTML will not affect the php code.
One solution would be to use the isset function like this:
$ctr = $_POST['counter'];
for ($x = 0; $x < $ctr; $ctr++)
{
isset($_POST["LastName$x"])?$lastname = $_POST["LastName$x"]:;
isset($_POST["FirstName$x"])?$firstname = $_POST["FirstName$x"]:;
}
If it is possible, instead of using LastNameN and FirstNameN names try using LastName[N] and FirstName[N], this way the result is an array and you can iterate through it with a foreach, meaning you will not need the counter and the index of the value will not be important:
foreach ($_POST["LastName"] as $i=>$lastname) {
if (!isset($_POST["FirstName"][$i])) {
// This should only happen if someone messes with the client side before posting
throw new Exception("Last name input does not have a related First name input");
}
$firstname = $_POST["FirstName"][$i];
}
If not, then you may have to use your $counter in a different way
$current = 0;
while ($counter) { // Stop only when i found all
if (isset($_POST["LastName$current"]) {
$counter--; // Found one
$lastname = $_POST["LastName$current"];
$firstname = $_POST["FirstName$current"];
}
$current++;
}
A better way to solve this would be to use arrays for Firstname and Lastname. Instead of calling them Lastname0 and Firstname0, then Lastname1 and Firstname1, call them all Lastname[] and Firstname[]. Give them ID's of Lastname0 and Firstname0 and so on for the delete function, but keep the names as arrays.
When the form is submitted use the following:
foreach($_POST['Lastname'] as $i => $lastname) {
$firstname = $_POST['Firstname'][$i]
//... code to save into the database here
}
Be warned though that in IE if you have an empty field it will not be submitted, so if Lastname0 has a value, but Firstname0 does not, then $_POST['Firstname'][0] will in fact contain the value of Firstname1 (assuming it has a value in it). To get around this you can use javascript to check if a field is empty when submitting the form, and if so put the word EMPTY in it.
Do not use counter if not required
A much easier way is to add array name when admore clicked.
Give a name like first_name[] in textbox
if you create form like that you can use foreach through $_POST['first_name']
try var_dump($_POST) in you php code to see how things goes on.
Inside your for loop, maybe you could try...
if ((isset($_POST["LastName$x"])) && (isset($_POST["FirstName$x"]))){
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
This will check if the variables exists before you try to do anything with them.

How to pull variable from one form to another form on same web page

I have a php web page that has 2 separate forms on it that both show results at the bottom of the page. The first form uses one drop-down menu (titled Quickshow) with 6 choices that filters the results when selected, with the top choice being the default selection when the page is opened. The second form has 6 drop-down menus, each with multiple choices, that filters the results once the "Filter Results" button is clicked.
My problem is when the second form is used, it is using the default selection from the first form instead of staying with the selected choice from the first form. I understand the code that is making the first choice the default, and also allowing it to change for the first form, but how do I keep (call?) the optional choices for the second form? Below is the code being used for both forms. The first part is the web (.php) page portion, the second part is on the template (.tpl) page that is being pulled over to the web page. I didn't write the pages, but am trying to fix the filter on it.
.php page
function enumRequests() {
$getQuickShow = 1;
if (!$_REQUEST['feature_quickshow'] == '') {
$getQuickShow = (int)$_REQUEST['feature_quickshow'];
}
$quickShow = eval(quickShow($getQuickShow));
$whereArray[] = (string)$quickShow;
if ($_REQUEST['resultsFiltered']) {
$quickShow = eval(quickShow($getQuickShow));
//$whereArray[] = (string)$quickShow;
foreach ($_REQUEST AS $key => $val) {
if ($val) {
$val = mysql_real_escape_string($val);
if (strpos($key, 'fld_') === 0) {
$newKey = str_replace('fld_','',$key);
$whereFragment = "{$newKey} = '{$val}'";
$whereArray[] = (string)$whereFragment;
}
}
}
}
}
.tpl page
Quick Show:[#quickshow]
Thanks in advance for any help I receive with this.
you can always refer to document.forms[1].mytxt.value = document.forms[0].utxt.value

checkbox's stay checked after pagination in php

Hello i want any checkbox i am gonna check, to stay checked after pagination.
here is the code:
foreach($test as $string){
$queryForArray = "SELECT p_fname,p_id FROM personnel WHERE p_id = " .$string["p_id"]. " ;" ;
$resultForArray = mysql_query($queryForArray, $con);
$rowfForArray = mysql_fetch_array($resultForArray);
?>
<td id="<?php echo $rowfForArray["p_id"]?>" onclick="setStyles(this.id)" ><?php echo $rowfForArray["p_fname"]?></td>
<td><input id="<?php echo $rowfForArray["p_id"]?>" class="remember_cb" type="checkbox" name="how_hear[]" value="<?php echo $rowfForArray["p_fname"]?>"
<?php foreach($_POST['how_hear'] as $_SESSION){echo (( $rowfForArray["p_fname"] == $_SESSION) ? ('checked="checked"') : ('')); } ?>/></td>
</tr>
<tr>
I am geting the data from a search result i have in the same page , and then i have each result with a checkbox , so that i can check the "persons" i need for $_Session use.
The only think i want is the checkbox's to stay checked after pagination and before i submit the form!(if needed i can post the pagination code, but he is 100% correct)
In the checkbox tag use the ternary operation, without that foreach inside him:
<input [...] value="<?php echo $rowfForArray["p_fname"]?>" <?php $rowfForArray["valueToCompareIfTrue"] ? "checked='checked'" : ''; ?> />
because the input already is inside of 'for' loop, then each time of the loop will create a new checkbox wich will verify if need to being check or not.
I hope I have helped you.
A few ways to tackle this:
(Straight up PHP): Each page needs to be a seperate form then, and your "next" button/link needs to submit the form everytime they click next. The submit data should then get pushed to your $_SESSION var. The data can then be extracted and used to repopulate the form if they navigate backwards as well. Just takes some clever usage of setting the URL with the proper $_GET variables for the form.
(HTML5): This will rely more on JavaScript, but basically you get rid of pagination and then just break the entire data set into div chunks which you can hide/reveal with JavaScript+CSS or use a library like JQuery.
(AJAX): Add event listeners to the checkboxes so that when a button is checked an asynchronous call is made back to a PHP script and the $_SESSION variable is updated accordingly. Again, this one depends on how comfortable you are with JavaScript.
Just keep in mind that PHP = ServerSide & JavaScript = ClientSide. While you can hack some PHP together to handle "clientside" stuff, its usually ugly and convoluted...
I did it without touching the database...
The checkbox fields are a php collection "cbgroup[]".
I then made a hidden text box with all the values which equal the primary keys of the selectable items mirroring the checkboxes. This way, I can iterate through the fake checkboxes on the current page and uncheck the checkboxes by ID that exist on the current page only. If the user does a search of items and the table changes, the selectable items remain! (until they destroy the session)
I POST the pagination instead of GET.
After the user selects their items, the page is POSTED and I read in the hidden text field for all the checkbox IDs that exist on that current page. Because PhP only tells you which ones are checked from the actual checkboxes, I clear only the ones from the session array that exist on the POSTED page from this text box value. So, if the user selected items ID 2, 4, 5 previously, but the current page has IDs 7,19, and 22, only 7, 19, and 22 are cleared from the SESSION array.
I then repopulate the array with any previously checked items 7, 19, or 22 (if checked) and append it to the SESSION array along with 2, 4, and 5 (if checked)
After they page through all the items and made their final selection, I then post their final selections to the database. This way, they can venture off to other pages, perhaps even adding an item to the dB, return to the item selection page and all their selections are still intact! Without writing to the database in some temp table every page iteration!
First, go through all the checkboxes and clear the array of these values
This will only clear the checkboxes from the current page, not any previously checked items from any other page.
if (array_key_exists('currentids', $_POST)) {
$currentids = $_POST['currentids'];
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$removeItems = explode($delimiter, $currentids);
foreach ($removeItems as $key => $del_val) {
//echo "<br>del_val: ".$del_val." - key: ".$key."<br>";
// Rip through all possibilities of Item IDs from the current page
if(($key = array_search($del_val, $itemList)) !== false) {
unset($itemList[$key]);
//echo "<br>removed ".$del_val;
}
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
// Leaves the previous paged screen's selections intact
$newSessionItems = implode(",", $itemList);
$_SESSION['materials'] = $newSessionItems;
}
}
}
Now that we have the previous screens' checked values and have cleared the current checkboxes from the SESSION array, let's now write in what the user selected, because they could have UNselected something, or all.
Check which checkboxes were checked
if (array_key_exists('cbgroup', $_POST)) {
if(sizeof($_POST['cbgroup'])) {
$materials = $_POST['cbgroup'];
$N = count($materials);
for($i=0; $i < $N; $i++)
{
$sessionval = ",".$materials[$i];
$_SESSION['materials'] = $_SESSION['materials'].$sessionval;
}
} //end size of
} // key exists
Now we have all the items that could possibly be checked, but there may be duplicates because the user may have paged back and forth
This reads the entire collection of IDs and removes duplicates, if there are any.
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$filtered = array();
foreach ($itemList as $key => $value){
if(in_array($value, $filtered)){
continue;
}
array_push($filtered, $value);
}
$uniqueitemschecked = count($filtered);
$_SESSION['materials'] = null;
for($i=0; $i < $uniqueitemschecked; $i++) {
$_SESSION['materials'] = $_SESSION['materials'].",".$filtered[$i];
}
}
}
$_SESSION['materials'] is a collection of all the checkboxes that the user selected (on every paged screen) and contains the primary_key values from the database table. Now all you need to do is rip through the SESSION collection and read\write to the materials table (or whatever) and select/update by primary_key
Typical form...
<form name="materials_form" method="post" action="thispage.php">
Need this somewhere: tracks the current page, and so when you post, it goes to the right page back or forth
<input id="_page" name="page" value="<?php echo $page ?> ">
if ($page < $counter - 1)
$pagination.= " next »";
else
$pagination.= "<span class=\"disabled\"> next »</span>";
$pagination.= "</div>\n";
Read from your database and populate your table
When you build the form, use something like this to apply the "checked" value of it equals one in the SESSION array
echo "<input type='checkbox' name='cbgroup[]' value='$row[0]'";
if (isset($filtered)) {
$uniqueitemschecked = count($filtered);
for($i=0; $i < $uniqueitemschecked; $i++) {
if ($row[0] == $filtered[$i]) {
echo " checked ";
}
}
}
While you're building the HTML table in the WHILE loop... use this. It will append all the select IDs to a comma separated text value after the loop
...
$allcheckboxids = "";
while ($row = $result->fetch_row()) {
$allcheckboxids = $allcheckboxids.$row[0].",";
...
}
After the loop, write out the hidden text field
echo "<input type='hidden' name='currentids' value='$allcheckboxids'>";

Categories