maspai
maspai

Reputation: 435

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"

Upvotes: 9

Views: 7022

Answers (5)

Amin
Amin

Reputation: 5

You can use this code before set_rules

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

Upvotes: -1

AdrienXL
AdrienXL

Reputation: 3008

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")

Upvotes: 5

Jorge Continuous
Jorge Continuous

Reputation: 51

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

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

So, when call the method, pass the default value:

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

Upvotes: 4

maspai
maspai

Reputation: 435

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

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

Upvotes: 8

Kenath
Kenath

Reputation: 630

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

Upvotes: 1

Related Questions