Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter POST/GET default value

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"
like image 329
maspai Avatar asked Feb 20 '15 05:02

maspai


2 Answers

Just found out not very long ago that I can also use ?:, eg.

$name = $this->input->post('name') ?: 'defaultvalue';
like image 164
maspai Avatar answered Nov 15 '22 21:11

maspai


You have to override the default behavior.

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")
like image 42
AdrienXL Avatar answered Nov 15 '22 20:11

AdrienXL