CodeIgniter POST/GET default value



如果POST/GET数据为空/假,我可以为其设置默认值吗,类似

$this->input->post("varname", "value-if-falsy")

所以我不必像那样编码

$a = $this->input->post("varname") ? 
     $this->input->post("varname") :
     "value-if-falsy"

不久前刚刚发现我也可以使用?:,例如

$name = $this->input->post('name') ?: 'defaultvalue';

您必须覆盖默认行为。

application/core中创建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;
    }
}

然后在你的控制器中:

$this->input->post("varname", "", "value-if-falsy")

它对我有效,我使用了@AdrienXL技巧。

只需创建application/core/MY_Input.php文件并调用父方法(您可以在CodeIgniter系统文件夹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);
        return ($value) ? $value : $default_value;
    }
    function get($index = NULL, $default_value = NULL, $xss_clean = FALSE)
    {
        $value = parent::get($index, $xss_clean);
        return ($value) ? $value : $default_value;
    }
}

因此,当调用该方法时,传递默认值:

$variable = $this->input->post("varname", "value-if-falsy");

您可以将代码块简化为以下

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;
}

您可以在set_rules 之前使用此代码

empty($_POST['varname']) ? $_POST['varname'] = 'value if empty' : 0;

最新更新