Skip to content

Set Value supports Indexes

Derek Jones edited this page Jul 5, 2012 · 10 revisions

This is my first item of contribution, so I might need a bit of guidance. This is a replacement for the default set_value() form helper that supports indexes in form elements. The index must be predefined, so my_field[] will not work, however my_field[2] will.

<?php
function set_value($field = '', $default = '')
{
    if (FALSE === ($OBJ =& _get_validation_object()))
    {
        if(strpos($field, '[') !== false && strpos($field, ']') !== false){
            $f = $field;
            $field = substr($f, 0, strpos($f, '['));
            $index = substr($f, strpos($f, '[')+1, (strpos($f, ']')-1) - strpos($f, '['));
        }
        if ( ! isset($_POST[$field]))
        {
            return $default;
        }
        
        if( is_array($_POST[$field]) && isset($index) && !empty($index)){
            if ( ! isset($_POST[$field][$index]) )
            {
                return $default;
            }
            
            return form_prep($_POST[$field][$index]);
        }

        return form_prep($_POST[$field]);
    }

    return form_prep($OBJ->set_value($field, $default));
}
?>

Category:Contributions::Helpers::Form

Clone this wiki locally