I'm trying to fill dynamicly a value in a form (Gravity form), so i'm using the function add filter :
add_filter( 'gform_field_value_champp', 'test' );
which fill the field "champp" with the return of the function test which is :
function test ( $fieldname)
{
return $fieldname ;
}
But i don't know why, nothing is returned. If i do a var_dump($fieldname), the variable is not empty.
Despite, if i do
function test ( $fieldname)
{
echo var_dump ($fieldname);
$fieldname = "value";
return $fieldname ;
}
The value "value" is well returned and it fill the form ... ! So i don't understand ...
Thanks
var_dump() is a 'void' function which means it does not return a value as a result of calling the function. And as such when the line:
// ...
echo var_dump($fieldname)
// ...
You are trying to echo an empty value.
So if you want to directly print the variable passed into the functions via the filter here's what your code would look like:
function test ( $fieldname ) {
echo $fieldname; // this is print the value of the variable
$fieldname = "value";
return $fieldname ;
}
Related
I'm trying to run a foreach loop to check if one of the required fields in a form is empty, and output the missing fields through an error array. Each of the variables is assigned to a $_POST variable.
However, once I call the function:
fields_empty($requiredFields, $fieldErrors);
It only runs once, and not looping through the error. Here's the full source code:
$requiredFields = array(
"First Name"=>$fname,
"Last Name"=>$lname,
"Email"=>$email,
"Password"=>$pass1,
"Confirm Password"=>$pass2,
"Country"=>$country,
"Address 1"=>$addr1,
"City"=>$city,
"State"=>$state,
"Postal Code"=>$pcode,
"Phone Number"=>$phone
);
$fieldErrors = array();
function fields_empty($requiredFields, $fieldErrors) {
global $fieldErrors;
foreach($requiredFields as $name => $field) {
if (empty($field)) {
array_push($fieldErrors, "$name is required.<br>");
return true;
}
}
}
fields_empty($requiredFields, $fieldErrors);
print_r($fieldErrors);
Output in browser:
Array (
[0] => First Name is required.
)
Also, this only happens when it's in a function. If I execute it without a function, it shows all the missing fields.
Remove return from your function. What return does is terminate the function and return whatever is passed with the return, here its set to true. Removing return will keep the loop running.
function fields_empty($requiredFields, $fieldErrors) {
global $fieldErrors;
foreach($requiredFields as $name => $field) {
if (empty($field)) {
array_push($fieldErrors, "$name is required.<br>");
}
}
}
i got a php function in Wordpress that get serialized user meta : like this
function get_allowwed_tournees_ids(){
$tournees = get_user_meta($this->ID, 'tournees',true);
$tournees = unserialize($tournees);
$tournees_ids = array();
foreach ($tournees as $key => $value) {
array_push($tournees_ids, $key);
}
var_dump($tournees_ids);
return $tournee_ids;
}
get_allowwed_tournees_ids() is in a class that extends WP_User
and when i want to call it :
$id_tournees = $current_user->get_allowwed_tournees_ids();
var_dump($id_tournees);
the var_dump inside the function returns me the unserialised array, and the second var_dump outside the function returns null.
Any idea ?? Thanks !
Because you are returning $tournee_ids which is never defined. I think you should
return $tournees_ids;
Is it possible to do in one line calling a method that returns an array() and directly get a value of this array ?
For example, instead of :
$response = $var->getResponse()->getResponseInfo();
$http_code = $response['http_code'];
echo $http_code;
Do something like this :
echo $var->getResponse()->getResponseInfo()['http_code'];
This example does not work, I get a syntax error.
If you're using >= PHP 5.4, you can.
Otherwise, you'll need to use a new variable.
What you can do is to pass the directly to your function. Your function should be such that if a variable name is passed to it, it should the value of that variable, else an array with all variables values.
You can do it as:
<?php
// pass your variable to the function getResponseInfo, for which you want the value.
echo $var->getResponse()->getResponseInfo('http_code');
?>
Your function:
<?php
// by default, it returns an array of all variables. If a variable name is passed, it returns just that value.
function getResponseInfo( $var=null ) {
// create your array as usual. let's assume it's $result
/*
$result = array( 'http_code'=>200,'http_status'=>'ok','content_length'=>1589 );
*/
if( isset( $var ) && array_key_exists( $var, $result ) ) {
return $result[ $var ];
} else {
return $result;
}
}
?>
Hope it helps.
Language itself does not support that for an array.
In case you can change what getResponseInfo() return:
You can create simple class, which will have array as an constructor parameter. Then define magical getter which will be just pulling the keys from the instance array
function __get($key)
{
return #content[$key]
}
Then you'll be able to do
echo $var->getResponse()->getResponseInfo()->http_code;
// or
echo $var->getResponse()->getResponseInfo()->$keyWhichIWant;
What i wrote is just proposal. The real __get method should have some check if the exists and so
I'm coding a worksheet app for a printer company.
I'm getting flood of forms.
For every single input field I have to check if the $_POST variables are set, and if, so echo back the value. (In case of some error, for example after a validation error, the user shouldn't retype the whole form)
Sample code:
if(isset($_POST['time'])&&!empty($_POST['time'])){echo $_POST['time'];}
I had to implement this about a hundred times.
So I tried to figure out some kind of function to make this simple and readable.
Something like this:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
But this wont work.
I have tried to pass in the $_POST for the $key variable like this:
if_post_echo($_POST['time'])
function if_request_echo($key, $default = "") {
if(isset($key)&&!empty($key)){
echo $key;
}else{
echo $default;
}
}
And I also tried this:
function if_request_echo($key, $default = null) {
return isset($_REQUEST[$key])&&!empty($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
}
Without any reasonable outcome.
The question:
How can I forge a function that looks for the necessary $_POST variable and returns it or if its unset then returns an empty string.
And is there a way to do this for $_GET and $_REQUEST, too? (Or simply duplicate?)
Your PHP testing function:
<?php
function test_req($key, $default = '') {
if(isset($_REQUEST[$key]) and
!empty($_REQUEST[$key])) {
return $_REQUEST[$key];
} else {
return $default;
}
}
?>
Then in your form HTML:
<input name="my_field" value="<?php echo htmlentities(test_req('my_field')); ?>" />
$_REQUEST (linked) is a PHP super global that contains both POST ($_POST) and GET ($_GET) request parameters.
If you only want to capture POST request parameters then it would be:
<?php
function test_req($key, $default = '') {
if(isset($_POST[$key]) and
!empty($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
}
?>
For example.
If you have a large amount of fields, I would propose that you also use an array of defaults:
$defaults = array(
"time" => "default",
"name" => "enter name here",
"text..." => "...",
);
$fields = array_filter($_POST) + $defaults;
$fields will then contain a list of form values with either the POST data or a preset default. No isset, see?
array_filter man page particularly: If no callback is supplied, all entries of input equal to FALSE will be removed. Goes some way to explaining the working behind this solution.
This should work:
function if_post_echo($key, $default = ''){
if(isset($_POST[$key]) AND !empty($_POST[$key]){
echo $_POST[$key];
}
echo $default;
}
If you're having problems I recommend that you try var_dump($_POST) or print_r($_POST) to see if everything has been properly posted.
Just to note, this is redundant:
isset($_POST[$key]) && !empty($_POST[$key])
An unset variable is going to always be "empty", so isset() is implied in your empty() call.
For your logic you can achieve the same result with just:
!empty($_POST[$key])
Your first function works perfectly to me.
Why do you think it doesn't work?
However, a better variant would be
function _post($key, $default = "") {
if(isset($_POST[$key])){
return $_POST[$key];
}else{
return $default;
}
}
To use it :
echo $_post($key); // You could define the message as a second parameter.
function requireArray( $array, $required ) {
foreach( $required as $k=>$v ) {
if ( !isset($array[$k]) || empty($array[$k]) )
return false;
}
return true;
}
#call like this:
requireArray($_POST, array('time', 'username', 'foo'));
If you want to know specifically:
function missingFrom( $array, $required ) {
$r = array();
foreach( $required as $k ) {
if ( !isset($array[$k]) || empty($array[$k]) )
$r[] = $k;
}
return $r;
}
Called like previous function.
Your method seems to work fine here:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
I made a simple input with the name test and the form method is POST and using echo if_post_echo('test');.
It posted on the page what was in the text box.
This feature is being added in PHP 7 as the "Null Coalesce Operator" using two question marks:
echo ($_GET['message'] ?? 'default-if-not-set');
https://wiki.php.net/rfc/isset_ternary
Hey all.
I have a processForm function and a displayForm function. If there are missing form fields the processForm function returns an array of missing fields. This is all fine and dandy until I try to include this array into the displayForm function. Here's the problem:
If I don't do this:
displayForm($missingFields=array());
then my validateField function throws a warning that it is expecting the parameter to be an array. However, this overwrites the array returned by the processForm function.
I hope I'm clear. Thanks for any help.
Full Code:
if(isset($_POST['action']) && $_POST['action'] = "login")
{
$messages = processForm();
}
processForm()
if($errorMessages)
{
return array("errors" => $errorMessages, "missing" => $missingFields);
}
else
{
$_SESSION['user'] = $user;
header("Location: index.php");
}
form.php
(!isLoggedIn())? displayForm($messages['errors']=array(),$messages['missing']=array()) : null;
These are the sections of the code I'm having trouble with.
Thanks again.
You don't set default argument values in the call, you set them in the signature, for example
function displayForm($arg1 = array()) {
...
}
When you write
displayForm($messages['errors']=array())
this is actually doing something like this
$messages['error'] = array(); // set $messages['error'] to an empty array
displayForm($messages['error']); // pass an empty array to displayForm
This is because in PHP, the return value from an assignment is the value assigned.
Why are you using this:
displayForm($messages['errors']=array(),$messages['missing']=array())
When you writing "$messages['errors']=array()", this is setting $messeges to blank array. So the parameter is blank. You can just write:
displayForm($messages['errors'],$messages['missing'])