Can I set default value for POST/GET data if it's empty/false, something like
$this->input->post("varname", "value-if-falsy")
?
So I don't have to code like
$a = $this->input->post("varname") ?
$this->input->post("varname") :
"value-if-falsy"
Thanks.
You have to override the default behaviour.
In application/core create MY_Input.php
class MY_Input extends CI_Input
{
function post($index = NULL, $xss_clean = FALSE, $default_value = NULL)
{
// Check if a field has been provided
if ($index === NULL AND ! empty($_POST))
{
$post = array();
// Loop through the full _POST array and return it
foreach (array_keys($_POST) as $key)
{
$post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean);
}
return $post;
}
$ret_val = $this->_fetch_from_array($_POST, $index, $xss_clean)
if(!$ret_val)
$ret_val = $default_value
return $ret_val;
}
}
And then in your controller :
$this->input->post("varname", "", "value-if-falsy")
It works for me, I have used the @AdrienXL trick.
Just create your application/core/MY_Input.php
file and call the parent method (you can find this methods inside CodeIgniter system folder system/core/Input.php
:
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
class MY_Input extends CI_Input
{
function post($index = NULL, $default_value = NULL, $xss_clean = FALSE)
{
$value = parent::post($index, $xss_clean);
if(!$value)
$value = $default_value;
return $value;
}
function get($index = NULL, $default_value = NULL, $xss_clean = FALSE)
{
$value = parent::get($index, $xss_clean);
if(!$value)
$value = $default_value;
return $value;
}
}
So, when call the method, pass the default value:
$variable = $this->input->post("varname", "value-if-falsy");
You can simplify the code block as below
public function post($index = NULL, $xss_clean = NULL, $default_value = NULL )
{
if( is_null( $value = $this->_fetch_from_array($_POST, $index, $xss_clean ) ) ){
return $default_value;
}
return $value;
}
Just found out not very long ago that I can also use ?:
, eg.
$name = $this->input->post('name') ?: 'defaultvalue';