Welcome Guest, Not a member yet? Register   Sign In
Default values with set_select()
#1

[eluser]BravoAlpha[/eluser]
I've been looking, unsuccessfully, for a way to provide a default value for a select element that I am building myself:
Code:
<select name="category_id">
&lt;?php foreach($categories->result() as $category): ?&gt;
    <option value="&lt;?php echo $category->category_id; ?&gt;"&lt;?php echo $this->validation->set_select('category_id', (string)$category->category_id); ?&gt;>&lt;?php echo $category->title; ?&gt;</option>
&lt;?php endforeach; ?&gt;
</select>

I came up with this replacement function:
Code:
function set_select($field = '', $value = '')
{
    if ($field == '' OR $value == '')
    {
        return '';
    }
    
    if (isset($_POST[$field]) AND $_POST[$field] == $value)
    {
        return ' selected="selected"';
    }
    else if (isset($this->$field) AND $this->$field == $value)
    {
        return ' selected="selected"';
    }
}
Any thoughts?
#2

[eluser]Michael Wales[/eluser]
Why not just use the default set_select() function?
#3

[eluser]BravoAlpha[/eluser]
[quote author="walesmd" date="1187422140"]Why not just use the default set_select() function?[/quote]
When the page is first loaded there is nothing in $_POST. (I suppose I could set $_POST myself for the select elements...)
#4

[eluser]Michael Wales[/eluser]
ah, sorry - misunderstood your post. Good show, good show.
#5

[eluser]alpar[/eluser]
I usually use the form helper, with the validation library, and if i need a default value, i look if the $_POST is empty or if $this->validation->run() returns false and $this->validation->error_string is empty, then i force the value that i need (usually when you have to populate a form from the database, it's a pretty fast to make solution, and didn't caused no trouble )
#6

[eluser]BravoAlpha[/eluser]
If I use `form_dropdown()`, then using `$this->validation->category_id` works fine.




Theme © iAndrew 2016 - Forum software by © MyBB