CodeIgniter Forums
A small helper function to compliment the existing form dropdown helper function. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=22)
+--- Thread: A small helper function to compliment the existing form dropdown helper function. (/showthread.php?tid=42637)



A small helper function to compliment the existing form dropdown helper function. - El Forum - 06-14-2011

[eluser]Basketcasesoftware[/eluser]
I discovered the documentation was vague on the arguments of the form_dropdown helper function about the item selected argument. I hoped for the best and fed it the display value of the entry I wanted as my default selection. Actually it goes off of the key instead. Since I'm working with rather long lists of option groups (196 countries by region) I needed something a little better. This is a first draft. It functions quite well as far as I've been able to test it.

Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('select_search'))
{
    function select_search($needle,$haystack)
        {
            $selected=array_search($needle,$haystack);

            if ($selected) return $selected;

            foreach ($haystack as $key => $val)
            {
                if(is_array($val))
                {
                    $selected=array_search($needle,$val);
    
                    if($selected) return $selected;
                }
            }
          
           return NULL;
        }
}
?>

I'm open for corrections and improvements. Smile


A small helper function to compliment the existing form dropdown helper function. - El Forum - 06-14-2011

[eluser]theprodigy[/eluser]
First off, nice function.

One quick question though. Can you add an example usage?

Is it as simple as:
Code:
<?php
echo form_dropdown('name', $select_opts, select_search($my_text,$select_opts));
?>



A small helper function to compliment the existing form dropdown helper function. - El Forum - 06-14-2011

[eluser]Basketcasesoftware[/eluser]
@theprodigy - Yep. Just that simple. Other than the need to load the helper file first. I didn't make any suggestions on that part, leaving it to the implementer how they wanted to name it.