Can Grails handle POST variables as an array? - php

If you post the following HTML into a PHP script:
<input type="hidden" name="var[0]" value="A" />
<input type="hidden" name="var[2]" value="C" />
<input type="hidden" name="var[1]" value="B" />
You would end up with a variable called $_POST['var'] (that is essentially a HashMap) whose keys/values look like this:
[0] => "A"
[1] => "B"
[2] => "C"
In PHP, I'm then able to do basic array logic on this, for instance I can see that count($_POST['var']) == 3, and I can iterate over it with a foreach statement.
Is there any way to accomplish this, or something similar, in Grails? I noticed that if I pass in the same sort of HTML to Grails, the result is much less intuitive than it is in PHP. What I want to do is to simply be able to access params.var[0], params.var[1], and so on, and likewise be able to examine things like params.var.length.
But this is not the case. What happens is that params.var is undefined, but instead I then have to access request.getParameter('var[0]'), which is obviously pretty useless.
I realize that I could change my HTML to something like this:
<input type="hidden" name="var" value="A" />
<input type="hidden" name="var" value="B" />
<input type="hidden" name="var" value="C" />
But this is far from ideal, because then I have to guarantee that the HTML inputs are in precisely the right order every time. In PHP, it doesn't really matter what order they appear in since I can specify that directly in the name attribute, and the language is smart enough to take care of it.
Am I missing something? Is there any way to accomplish this in Grails?

Actually it does by default, when binding data. See http://grails.org/doc/latest/guide/theWebLayer.html#dataBinding Binding To Collections And Maps.
The data binder can populate and update Collections and Maps. The following code shows a simple example of populating a List of objects in a domain class:
class Band {
String name
static hasMany = [albums: Album]
List albums
}
class Album { String title Integer numberOfTracks }
def bindingMap = [name: 'Genesis',
'albums[0]': [title: 'Foxtrot', numberOfTracks: 6],
'albums[1]': [title: 'Nursery Cryme', numberOfTracks: 7]]
def band = new Band(bindingMap)
assert band.name == 'Genesis'
assert band.albums.size() == 2
assert band.albums[0].title == 'Foxtrot'
assert band.albums[0].numberOfTracks == 6
// ...
Also if you want to deal with this on your own, you can of course write it yourself. E.g.:
params.collect{it=~/${name}\[(\d+)\]/}.findAll().collectEntries{[it.group(1).toInteger(), params[it.group(0)]]}

Related

accessing dynamic variables from a form

I used to have register_globals turned ON (I know - bad bad bad horribly bad) and now I'm changing it up and the specific application is my DVD collection. Adding a DVD presents a set of checkboxes for genres/categories (i.e. drama, comedy, etc). Each genre is coming out of a database table so I can add new genres as needed. The problem here is that it generates its fieldname (checkbox name) from an abbreviation in this db table.
IE I'll have:
<input type="checkbox" name="drama" />Drama
<input type="checkbox" name="bio" />Biography
(etc)
So what I was doing before was, with the script that made the entries, it would run through the list of abbreviation names and if it matched the input ($_POST['drama']), it would indicate that this DVD falls into that category.
The present problem now is, with global variables turned off, how can I dynamically gather those $_POST values? I tried looping through the database and spitting out a concatenated variable trying to declare them in this format:
$drama=$_POST['drama'];
This didn't work because I'm mixing up functions with variables and it made a horrible mess.
I hope someone has an answer on how I can read in the $_POST array and use it.
Given some checkboxes like this:
<input type="checkbox" name="genre[]" value="drama" />
<input type="checkbox" name="genre[]" value="comedy" />
<input type="checkbox" name="genre[]" value="mystery" />
you'd end up with $_POST['genre'] being an array. Asuming drama and mystery are checked off, you'd end up with
$_POST['genre'] = array(
0 => 'drama',
1 => 'mystery'
);
Remember that unchecked checkboxes do not submit with the form, so if you get an entry in $_POST['genre'], it was selected in the form.
To check if a category in your DB was selected, you could do something like
if (in_array('drama', $_POST['genre'])) {
... drama is selected
}
See this example:
foreach ($_POST as $key => $value) {
echo "name: $key, value: $value<br />";
}

Return value from element while showing another

Hi lets say I'm showing a numeric value in an element (not sure what element to use), what i want to achieve is once the numeric value is clicked (Thinking of onclick="this.form.submit();" or submit button) it will submit different designated value from the numeric value let us say. Apple then my sql query would retrieve apple and use it. NOTE: I have multiple numeric values and multiple designated values for each numeric value as an example it looks like this:
(numeric value) = (designated value)
15123 = apple
24151 = orange
39134 = peach
Here so far is what i have.
<input type='submit' name='searchthem' placeholder='<?php echo $numeric_value; ?>'
value='apple'>
** NOTE i have multiple numeric values with different designated value
And this is the SQL in the same page:
SELECT * from tbl_fruits where fruit_name='".$_POST['searchthem']."' ;
Would appreciate some help and ideas, If there is confusion please comment so i may further clarify.
Use select element and just submit the form so that it can process the values. if you wish to use AJAX, use some javascript and output the result in the browser.
If I understand your problem correctly you should add an array for the definition terms and do it like this:
<input type="hidden" name="searchterm" value="<?php echo $numeric_value; ?>" />
<input type='submit' name='send' value="<?php echo $names[$numeric_value]; ?>" />
Then in PHP switch through the values:
switch($_POST['searchterm']){
case(15123) $term = 'apple';break;
case(24151) $term = 'ornage';break;
case(39134) $term = 'peach';break;
}
This will secure your SQL query, too. [Beware: Never use unfiltered input (i.e. $_POST in your example) from the browser in SQL queries!]

html and javascript same name for multiple inputs - how to?

I have never done anything like this, and I would like to know how to do it. I need to put 4 inputs into a sub array if it is field out
I know that when i $_POST the form to the server it sends the names of the inputs but how do I get the input to be allowed to have the same name
for example
the sub array i need it to be in is offers
here is what i dont know. How do i get the following inputs
<input name="offers[]['minspend']" value="15.00"/>
<input name="offers[]['minspend']" value="5.00"/>
<input name="offers[]['minspend']" value="19.00"/>
<input name="offers[]['minspend']" value="8.00"/>
<input name="offers[]['minspend']" value="30.00"/>
<input name="offers[]['minspend']" value="7.00"/>
<input name="offers[]['minspend']" value="100.00"/>
<input name="offers[]['minspend']" value="10.00"/>
is this correct or wrong?
thanks
It depends a bit on the back end technology that processes your request (java, php, whatnot), but from an html standpoint multiple elements with the same name will just send their value with the same parameter name. You don't need any special [] syntax.
GET /mypage.html?offer=15.00&offer=5.0&offer=19.0 (etc, could be post too)
Most languages that provide built in support for html requests represent this request as a map, with a key named "offer" and a value that is an array or list containing the values submitted.
For example http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()
This form
<input name="offers['minspend'][]" value="15.00"/>
<input name="offers['minspend'][]" value="5.00"/>
<input name="offers['minspend'][]" value="19.00"/>
<input name="offers['minspend'][]" value="8.00"/>
<input name="offers['minspend'][]" value="30.00"/>
<input name="offers['minspend'][]" value="7.00"/>
<input name="offers['minspend'][]" value="100.00"/>
<input name="offers['minspend'][]" value="10.00"/>
on doing var_dump($_POST) [assuming form method=post] give:
array(1) {
["offers"] = > array(1) {
["\'minspend\'"] = > array(8) {
[0] = > string(5)"15.00"
[1] = > string(4)"5.00"
[2] = > string(5)"19.00"
[3] = > string(4)"8.00"
[4] = > string(5)"30.00"
[5] = > string(4)"7.00"
[6] = > string(6)"100.00"
[7] = > string(5)"10.00"
}
}
}
So, that is how you do it.
you can remove 's around minspend. they aren't needed.
You were almost there. offers[]['minspend'] means that you get:
array(){
array(){
'minspend' => "15.00"
}
array(){
'minspend' => "5.00"
}
.. and so on
}
So what is happening is, when you do something like arr[] = 1, 1 is inserted into array arr.
Well first let me tell you what i understood from the question. You want multiple input fields to have same name and then you want to select them all to perform some action. If this is the case i'd like to present a different approach - why don't you assign same class (cssclass) to all the controls you want to have same name. That way you'll be able to select them all together using document.getElementsByClassName("yourclassName"). which will return you an array of all the elements having class attribute as yourclassName.
Or if you wanna stick to name then you can use document.getElementsByName("elementName"); which returns you an array of elements having name as elementName.
Hope its helpful.

Modifying $_POST variable before submitting

I'm making a quiz generator, and I have an HTML form with radio buttons for multiple choice answers. Right now, when I submit my form, the contents of the $_POST variable looks like this when I submit it:
Array ( [a1] => Bob [a2] => Bobby )
(Bob and Bobby are the radio button choices I picked)
I'm generating this form using a PHP function, which returns an array of answers in addition to echoing the HTML form. Is there a way to modify the $_POST variable to have an 'answer' field (for checking my answers), like this:
Array( [a1] => Bob [a2] => Bobby [answers] => Array( [0] => Bob [1] => Bilbo ))
The above was one way I thought of to check answer array with $_POST array.
Edit: More info on what I have so far:
I have a PHP function getTest() that echoes the HTML form, and returns an array with the correct answers.
getTest() generates each question randomly, and as such the correct answers are random.
The main problem is that I have two separate PHP files, questions.php and verify.php.
questions.php echoes the form using getTest(), and has the array of answers.
verify.php only has the contents of $_POST, BUT NOT the array of correct answers.
Is there a better way to check the results of the form submission in general? Thanks!
The best way to do a quiz is to have an answers array and a user input array. Loop through one and compare to the other using the same increment.
You can take all of your post variables and create an array print_r($_POST); Then, loop through this.
$inputArray = //the post data into an array
$answerArray = array('a','b','a');
$numCorrect = 0;
for($a = 0; $a < count($inputArray); $a++)
{
if($inputArray[$a] == $answerArray[$a])
{
$numCorrect++;
}
}
If you want to transmit the answers when submitting the form, you could use inputs of hidden type (like ) which are invisible on the page. However it only takes the user checking the source HTML of the page to see these answers, so it might not be good for your use. Hope this helps
I think what you need to do is a have a look at sessions.
That way on questions.php you can save the answers to a session variable,
Then on verify.php you can read the answers from the session variable and compare them to answered supplied by the $_POST variable
If you really wanted to, you could probably just use a hidden field in your form for submitting an answer array. However, anyone can change your source and modify what the correct answer is.
The best way is to just have an array in your processing script with the same keys (a1, a2), but with the correct answers.
Your processing script would look like this:
$answers = array('a1'=>'Robert', 'a2'=>'Hobo');
foreach($_POST as $key => $value)
{
if (!array_key_exists($key, $answers))
{
continue;
}
if (trim($value) == $answers[$key])
{
// correct
}
else
{
// incorrect
}
}
If you want $_POST to contain an array you can simply use the bracket array notation on the name field of your form.
For example:
<fieldset class="Question1">
<input type="radio" name="answers[]" value="Question1Answer1">Question1Answer1<br>
<input type="radio" name="answers[]" value="Question1Answer2">Question1Answer2<br>
<input type="radio" name="answers[]" value="Question1Answer3">Question1Answer3<br>
</fieldset>
<fieldset class="Question2">
<input type="radio" name="answers[]" value="Question2Answer1">Question2Answer1<br>
<input type="radio" name="answers[]" value="Question2Answer2">Question2Answer2<br>
<input type="radio" name="answers[]" value="Question2Answer3">Question2Answer3<br>
</fieldset>
<fieldset class="Question3">
<input type="radio" name="answers[]" value="Question3Answer1">Question1Answer1<br>
<input type="radio" name="answers[]" value="Question3Answer2">Question1Answer2<br>
<input type="radio" name="answers[]" value="Question3Answer3">Question1Answer3<br>
</fieldset>
(Note that the fieldset tag is optional, I just included it to group things together)
The output in post will be an array $_POST['answers'] that will have one element for each question. So if you selected answer 1 for question 1, answer 2 for question 2, and answer 2 for question 3 you'd have:
$_POST['answers'] = [ 'Question1Answer1', 'Question2Answer2', 'Question3Answer2' ]
Not sure, but looks like you are asking for solution Y, whereas your problem is X (XY Problem)
The XY problem is when you need to do X, and you think you can use Y
to do X, so you ask about how to do Y, when what you really should do
is state what your X problem is. There may be a Z solution that is
even better than Y, but nobody can suggest it if X is never mentioned.
Usually it is not recommended to modify $_POST array, and also not to transmit Answers with the questions to client-side. Instead, the approach should be that because questions.php dont need answers, but verify.php does, so only verify.php shoul have access to answers.
For example, answer-lists are never transported to examination halls along with the question papers on the occasion of exams.
I have taken the liberty to modify your code structure. If you still want to go with your own code, please post it, and then you can get the answers you want.
Try to use this:
question.php:
<form action="verify.php" method="POST">
<fieldset class="Question1"> Complete this: ___<b>bar</b>
<input type="radio" name="answers[]" value="foo">Foo<br>
<input type="radio" name="answers[]" value="too">Too<br>
<input type="radio" name="answers[]" value="cho">Cho<br>
</fieldset>
<fieldset class="Question2"> Complete this: ___<b>overflow</b>
<input type="radio" name="answers[]" value="stack">Stack<br>
<input type="radio" name="answers[]" value="stock">Stock<br>
<input type="radio" name="answers[]" value="stick">Stick<br>
</fieldset>
</form>
answers.php:
//correct answers
$answers = array("foo", "stock");
verify.php:
include("answers.php");
$user_answers = $_POST["answers"];
$user_answers_count = count($user_answers);
$error = "";
for($i=0;$i<$user_answers_count;$i++)
if($user_answers[$i] !== $answers[$i]) //verify
$error[] = "Answer for Question ".($i+1)." is wrong!";
if(empty($error))
//Notify that user has passed the Quiz
else
//Notify that user has NOT passed the Quiz
//print the $error array
Couple of Notes:
I have used answers.php as a different file, but if there is no special requirement, consider merging answers.php & verify.php (put answers.php code on top of verify.php) Even better, you could also merge all these three files into one.
I have assumed that $_POST is sanitized.
Sequence of Questions & answers array is same. i.e. answers[foo] is correct answer for $_POST["answers"][foo]

Assistance with understanding php urls

I'm looking at websites that use php and I seea[]=val1 instead ofb=val2. My question is why are there brackets in the url? What type of code would produce this effect?
Why Are the Brackets in the URL?
The brackets are in the url to indicate that val1 is to be assigned the next position in the array a. If you are confused about the blank part of the bracket, look at how php arrays work.
What Kind of Code Would Produce This?
As for the code that would create such a url, it could either be an explicit definition by the coder or some other script, or it could be somehow created by a form using the method="get" attribute.
Example:
To create this, you can define an array as the name of an input field like so:
<form method="get">
<input name="a[]" ... />
<input name="a[]" ... />
<input name="a[]" ... />
</form>
Or you can just make a link (the a tag) with this url:
Click Me!
To parse this url with PHP, you would use the $_GET variable to retrieve the values from the url:
<?php
$a = $_GET['a'];
$val1 = $a[0];
$val2 = $a[1];
$val3 = $a[2];
...
print_r($a);
?>
The printout of the print_r($a) statement would look like this (if you wrapped it in a <pre> tag):
Array (
a => Array (
0 => 'val1',
1 => 'val2',
2 => 'val3'
)
)
That is the syntax for appending a new element to an array. There should be dollar signs preceding each variable:
$a[] = $val1;
You would see input fields on the page before, like:
<input name="color[]" type="checkbox" value="red">
<input name="color[]" type="checkbox" value="blue">
<input name="color[]" type="checkbox" value="green">
wherein the user could select multiple responses and they would be available in the $color array in the $_GET (and URL) of the action page, showing up like you describe.
(Similarly it could also be hidden variables passed as an array that are not based on user input.)

Categories