<?php
module_load_include('inc', 'node', 'node.pages');
$node_form = node_add('post');
print drupal_render($node_form);
?>
This is my code snippet.
The problem is, that I want to pass several parameters for pre-selected default values:
/node/add/post?field_type=3&field_post_id=122
Like the example above.
How can I add parameters (such as "field_type=3" & "field_post_id=122") to my PHP code example above?
Don't use node_add here, there are several ways to do that (as usual):
Have a look at the prepopulate module
If the module does not fit, alter the node form by using hook_form_FORMID_alter as described in the API.
If you don't like McGo's answer (which is good) for some reason, here's an example of how to do that:
$node_form = node_add('post');
foreach ($_GET as $key => $value) {
// this query string is a field prepop.
if (strpos($key, 'field_') === 0) { // === to prevent a false negative.
// this field exists on the form
if (!empty($node_form[$key])) {
$node_form[$key]['#default_value'] = $value;
}
}
}
While untested, something like this should work.
Related
I have some legacy code which I want to update. In that version of the code ( which was a backend for jqGrid ), the search parameters where sent to the server in the POST variables. The POST key is the field name, and the value is the search value. Starting a few years ago I started only accessing POST variables via the filter_input function, which was suggested by my IDE. However I haven't found a recommended way to loop through the POST variables without accessing the POST variable directly.
The portion of the legacy code for search parameters is like this:
/*
* Search Filter
*/
if ($search){
$where_string = ' where ';
foreach ($_POST as $key => $value){
if (in_array($key,array('_search','nd','rows','page','sidx','sord','arg1','arg2'))==true){
continue;
}
//put in functionality to search for exact values
//to search for exact values, include a * character before the value you are searching for
if (strpos($value, "*") === 0){
//exact search
$value = substr($value,1);
}else{
//like search
$value = "%".$value."%";
}
$key = $mysqli->real_escape_string($key);
$value = $mysqli->real_escape_string($value);
$where_string .= '`'.$key.'` like "'.$value.'" AND ';
}
$where_string = rtrim($where_string,' AND ');
}
The warning that my IDE gives is: Do not Access Superglobal $_POST Array Directly.
on the foreach line. Just not sure if I am supposed to avoid this kind of loop completely, or if there is a way to use filter_input with that. It is kind of a generic code for any table. Thanks for the guidance.
I have a large HTML form posting many fields to a PHP page. I'm assigning all those fields to PHP variables one by one. Is there a way to put to create a function to auto assign the POST value to a PHP variable?
This is my code now:
if (!empty($_POST["x"])) {
$x = clean_post($_POST["x"]); }
if (!empty($_POST["y"])) {
$y = clean_post($_POST["y"]);
}?>
Thanks!
You can do this using the array_keys() function and a foreach-loop like this:
foreach (array_keys($_POST) as $key) {
${$key} = $_POST[$key];
}
But why not use the $_POST array in the first place?
Yes, but it's a rubbish idea. They actually had this in PHP, but removed it. It was called register_globals. So for instance, $_POST['name'] would automatically have $name created.
If you insist on this terrible idea, you should be able to do it like this:
foreach ($_POST as $key => $value) {
$$key = $value;
}
Don't do it though! Read this for more info https://secure.php.net/manual/en/security.globals.php
So here I am again trying to find better ways of doing things. 90% of tutorials do things the normal way below:
if (isset($_POST['name']) && isset($_POST['password'])) {
// Does some stuff...
}
It is fine but it does seem too static since I prefer something far more dynamic. For example lets say looping through all $_POST arrays within a contact form. This way I can change the name or the fields to whatever I want or add more...my code will always handle the rest.
I know a foreach loop would come in handy but, as someone new to the world of programming and php I thought you could show me how something like this is done. So how do I replace the above with a for loop? I am not sure where to start.
try this:
$check=true;
if(isset($_POST)){
foreach($_POST as $key=>$value){
if(!isset($_POST[$key]){
$check = false;
break;
}
}
}
based on $check you can verify if it was properly sent or not.
Another approach is to have a sort of verification because it is possible you might not get the key in $_POST
$keys =array("input1","input2");
$check=true;
if(isset($_POST)){
foreach($keys as $input){
if(!array_key_exists($input,$_POST)){
$check = false;
break;
}
}
}
Well you could try something like this :-
<?php
$inputNames = array("input1","input2");
foreach($inputNames as $input)
{
if (isset($_POST["$input"]) && isset($_POST["$input"])) {
// Does some stuff...
}
}
?>
Make an array with the names of all your input tags, and then simply do a foreach between them. In this way, you always only need to edit the names array.
You can always use foreach loop like that:
foreach($_POST as $key => $value){ echo '$_POST["'.$key.'"] = "'.$value.'"'}
But remember, that anyone, can modify your form, prepare some post statement and send data that can create little mess with your code. So it`s good way to validate all fields.
Dynamic validation is of course possible, but you need to do it right!
I am trying to get multiple value from user input from text field and want to explode or keep adding into if condition statement
Here is my code
foreach ($list['post'] as $item) {
if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ){
$this->list_post($item);
}
}
Now what exactly I am looking for is in if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ) I want allow user to add multiple category ID and each ID will add AND and further id code AND ($item['single']['catid'] != 4)
I never done this before and don't know either this is proper way to do or any other possible better way.
Thanks a lot
You should have some kind of an array of the category IDs you want to check for, for example:
$categories = array(8, 4);
Then you could use something like the in_array(needle, haystack) built-in function of PHP.
Your if condition would become like that one: if (!in_array($item['single']['catid'], $categories)) {.
You should be using the above, but I am going to give you an idea of how it works, so you can understand the principle for more complex issues:
function exists($target, $array) {
foreach ($array as $element) { // Go through each element in the array
if ($element == $target) { // Check to see if any element there is what you are searching for
return true; // Return true, that it does exist, and stop there.
} else {
// Just ignore it...
}
}
return false; // If you get here, it means nothing returned true, so it does not exist...
}
To be used as if (exists($item['single']['catid'], $categories)) {.
It wouldn't work if it was "inside" the if statement because you have to do some processing before evaluating if it exists or not. So you either could have done that before the if statement, and store the result in a variable, or use a function (which PHP provides).
Hopefully the concept will help you fir more complex problems...
Note: this assumes your input is in the form of an array, which you can build via various ways, if not provided as is directly.
Update:
The input you get via the input field is sent through form, to which you specify either POST or GET as a method. Assuming it is POST that you are using, this is how you'd get the input as a string as it was entered in the text field:
$categories_string = $_POST['the_name_field_in_the_input_tag'];
After that you have to understand it as a list of items, let's say separated by commas: 1,3,5,8. Then this is simply separating by commas. You can use explode($delimiter, $string). Like that:
$categories_array = explode(',', $_POST['categories']);
But you cannot trust the input, so you could get something like 1, 2, 3,5,6. The spaces will mess it up, because you will have spaces all around. To remove them you can use trim for example.
$categories = array(); // Create the array in which the processed input will go
foreach ($categories_array as $c) { // Go through the unprocessed one
$categories[] = trim($c) * 1; // Process it, and fill the result. The times one is just so that you get numbers in the end and not strings...
}
Then you can use it as shown earlier, but keep in mind that this is just an example, and you might not even need all these steps, and there are much more efficient ways to process this input (regular expressions for example). But the concern here is not sanitizing input, but keep in mind you will need to do that eventually.
Hope it's clear enough :)
You might be better off with in_array() for checking a value against a variable number of possibilities.
I'm not sure I understand your problem. You want user to be able to input different values, e.g.:
$string = "5, 6, 7, 8, 10";
Afterwards, you want to check if 'catid' is not in that array and if it isn't you want to run $this->list_post($item);
If so, then you should use something like this:
$values = explode(", ", $string); //make array from values
foreach ($list['post'] as $item) {
if (!in_array($item['single']['catid'], $values)) { //check whether catid is in array
$this->list_post($item); // execute whatever you want
}
}
Hope it helps.
Could anyone tell me why I am not retrieving info from a form I have submited within a wordpress template? The variables are being passed but they have no values?!?
New answer to an age-old question!
I came across this post, which didn't help, and wrote my own utility (happily shared and feel free to improve)
/* Get Parameters from $_POST and $_GET (WordPress)
$param = string name of specific parameter requested (default to null, get all parameters
$null_return = what you want returned if the parameter is not set (null, false, array() etc
returns $params (string or array depending upon $param) of either parameter value or all parameters by key and value
Note: POST overrules GET (if both are set with a value and GET overrules POST if POST is not set or has a non-truthful value
All parameters are trimmed and sql escaped
*/
function wordpress_get_params($param = null,$null_return = null){
if ($param){
$value = (!empty($_POST[$param]) ? trim(esc_sql($_POST[$param])) : (!empty($_GET[$param]) ? trim(esc_sql($_GET[$param])) : $null_return ));
return $value;
} else {
$params = array();
foreach ($_POST as $key => $param) {
$params[trim(esc_sql($key))] = (!empty($_POST[$key]) ? trim(esc_sql($_POST[$key])) : $null_return );
}
foreach ($_GET as $key => $param) {
$key = trim(esc_sql($key));
if (!isset($params[$key])) { // if there is no key or it's a null value
$params[trim(esc_sql($key))] = (!empty($_GET[$key]) ? trim(esc_sql($_GET[$key])) : $null_return );
}
}
return $params;
}
}
Just came up against the same/similar issue; it is not ideal to use get variables on Wordpress as the URL is structured using mod_rewrite and has some reserved query parameters. The Wordpress Docs on query vars gives you a bit of a list, but it is not comprehensive.
In summary, the variables you were using may have been one of those reserved or modified or handled by Wordpress?
(I know this is an old question but it needs an answer or clarification.)
Please check form method
<form name="frmlist" method="post">
Try with this
print var_dump($_GET);
print var_dump($_POST);