Creating radio elements in some content management systems can result into writing a lot of code. Just in case your radio group with multiple options is getting a value from a database and/or a form. There need to be a check for every posted value for every option. This function will do all this work for you, just create two arrays, one for the values and labels and for the related html code. It's up to the user if he uses 2 or more elements in one group. The function works with $_POST and $_GET data.
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.in/ */ $values = array('google'=>'Google Search', 'link'=>'Link on some website', 'advert'=>'Advertisement', 'news'=>'News'); $html_elements = array('before'=>'', 'after'=>' ', 'label'=>' '); function radioGroup($formelement, $values, $html, $def_value = '') { $radio_group = ''."\n"; $radio_group .= (!empty($html['label'])) ? $html['label']."\n" : ''; if (isset($_REQUEST[$formelement])) { $curr_val = stripslashes($_REQUEST[$formelement]); } elseif (isset($def_value) && !isset($_REQUEST[$formelement])) { $curr_val = $def_value; } else { $curr_val = ""; } foreach ($values as $key => $val) { $radio_group .= $html['before']."\n"; $radio_group .= '' : ' />'; $radio_group .= ' '.$val."\n".$html['after']."\n"; } $radio_group .= ''."\n"; return $radio_group; } // place this code between the form tags: // notice 'advert' could be a database value too echo radioGroup('test', $values, $html_elements, 'advert'); ?>
0 comments:
Post a Comment