Im trying to do chained select using jquery chained, but codeigniter echo form dropdown does not allow individual assignment of CLASS.
I would like to assign CLASS to each list like the example below.
<select name="hardware">
<option class="printer" value="" selected="selected"></option>
<option class="printer" value="EPSON">EPSON</option>
<option class="printer" value="HP">HP</option>
<option class="hdd" value="WD">WD</option>
<option class="hdd" value="SEAGATE">SEAGATE</option>
</select>
and here is the codeigniter form dropdown
VIEW PAGE:
<form action="" method="">
$select = 'hardware';
echo form_dropdown('hardware', $hardware,set_value('hardware',$this->input->post('hardware'))); ?>
</form>
I have changed the select form to this.
<select name="supplier">
<?php foreach($supplier as $row){ ?>
<option value="<?php echo $row['supplier'];?>"><?php echo $row['supplier'];?>
</option>
<?php }?>
</select>
how can i return the selected value after a failed validation?
This is not possible using the form_dropdown() because codeigniter is not allowing any parameter to set the "extra" attributes like class in the option tag.
Check this function : this is the core function form_dropdown() :
function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '')
{
if ( ! is_array($selected))
{
$selected = array($selected);
}
// If no selected state was submitted we will attempt to set it automatically
if (count($selected) === 0)
{
// If the form name appears in the $_POST array we have a winner!
if (isset($_POST[$name]))
{
$selected = array($_POST[$name]);
}
}
if ($extra != '') $extra = ' '.$extra;
$multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';
$form = '<select name="'.$name.'"'.$extra.$multiple.">\n";
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val) && ! empty($val))
{
$form .= '<optgroup label="'.$key.'">'."\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
}
$form .= '</optgroup>'."\n";
}
else
{
$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
}
}
$form .= '</select>';
return $form;
}
what you want to do, you will have to create your own helper,See "Extending Helpers" here in the docs. I would do what is says and copy a "MY_helper.php" version to your application folder; don't mess with the core unless you really have to.
http://ellislab.com/codeigniter/user-guide/general/helpers.html
You could use the values array and set a class and item in an array (and change the foreach near line 327 in the helper) or pass another array and check it in the foreach.
Related
I'd like to add "selected" attribute to a combo box. This is my PHP:
if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }
if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }
if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }
if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }
I may have over hundreds of IF's.
I've tried this one, but It seems not working:
for($a=1; $a<=4; $a++){
if($results['status'] == $a)
{ $ok = "selected"; }
else
{ $ok = ""; }
}
I'd like to make it as simple as possible. maybe 1 or 2 line. Because I have many combo box that should be treated this way
Edit (My combo box):
<select>
<option value="1" <?php echo $ok1; ?>>A</option>
<option value="2" <?php echo $ok2; ?>>B</option>
<option value="3" <?php echo $ok3; ?>>C</option>
<option value="4" <?php echo $ok4; ?>>D</option>
</select>
Since $results['status'] can only have 1 value, use dynamic variable names to make your life easy!
// initialize all 4 to blank
for($a=1; $a<=4; $a++){
${"ok" . $a} = "";
}
// set the one that is selected
${"ok" . $results['status']} = "selected";
This answer is very scalable, you can just change the number on the "for" line from 4 to 1000 and it works with no extra code added.
You can do this way,
<?php
// status list array
$selectValues = array(1, 2, 3, 4);
echo '<select name="combo_name">';
foreach($selectValues as $value){
$selected = "";
if($results['status'] == $value){
$selected = ' selected="selected" ';
}
echo '<option '.$selected.' value="'.$value.'">'.$value.'</option>';
}
echo '</select>';
?>
All you have to do is make an array and loop through it-
<?php
$results_status = 3; // What ever your retrieve variable value is. In your case: `$results['status']`
$arr = array("1" => "A",
"2" => "B",
"3" => "C",
"4" => "D"
);
?>
<select>
<?php
foreach($arr as $key => $val){
$sel = ($results_status == $key) ? "selected='selected'" : "";
?>
<option value="<?php echo $key?>" <?php echo $sel; ?>><?php echo $val?></option>
<?php }?>
</select>
You need to check every time for the selected value in the combo box.
Hope this helps
$combolength - the number of options in combo
$ok = array_fill(0, $combolength - 1, '');
switch ($results['status']) {
case $results['status']:
$ok[$results['status']]= 'selected';
break;
}
I personally think "simplify" what you already have is not the way to go about this. If you are not using a framework, I think you should instead ask how to make your script reusable, especially since you say "I have many combo box(es) that should be treated this way." Not using a contained element like a function/method sounds like a lot of extra work from a hardcoding standpoint. I personally would create a class that you can make form fields standardized and that you can feed an array into with dynamic key/value arrays. Simple example:
/core/classes/Form.php
class Form
{
# The idea here is that you would have many methods to build form fields
# You can edit this as you please
public function select($settings)
{
$class = (!empty($settings['class']))? ' class="'.$settings['class'].'"':'';
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':'';
$selected = (!empty($settings['selected']))? $settings['selected']:false;
$other = (!empty($settings['other']))? ' '.implode(' ',$settings['other']):'';
ob_start();
?>
<select name="<?php echo $settings['name']; ?>"<?php echo $other.$id.$class; ?>>
<?php foreach($settings['options'] as $key => $value) { ?>
<option value="<?php echo $key; ?>"<?php if($selected == $key) echo ' selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
To use:
# Include the class
require_once(__DIR__.'/core/classes/Form.php');
# You can use $form = new Form(); echo $form->select(...etc.
# but I am just doing this way for demonstration
echo (new Form())->select(array(
'name'=>'status',
'class'=>'classes here',
'id'=>'select1',
'other'=>array(
'data-instructions=\'{"stuff":["things"]}\'',
'onchange="this.style.borderColor=\'red\';this.style.fontSize=\'30px\'"'
),
# Options can be assign database returned arrays
'options'=>array(
'_'=>'Select',
1=>'A',
2=>'B',
3=>'C',
4=>'D'
),
'selected'=>((!empty($results['status']))? $results['status'] : '_')
));
Gives you:
<select name="status" data-instructions='{"stuff":["things"]}' onchange="this.style.borderColor='red';this.style.fontSize='30px'" id="select1" class="classes here">
<option value="_">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
I am working with a multi-select and GET method.I want multiple options selected when the form is reloaded after submitted based on the $_GET method from url parametres.i have associated URL parametres is cuisine%5B%5D=indian&cuisine%5B%5D=thai.Actually multi-select is about cuisine.
And my codes are below:
<select name="cuisine[]" class="selectpicker show-tick form-control" data-selected-text-format="count > 3" data-done-button="true" data-done-button-text="OK" multiple>
<?php
$selected_cuisine = $_GET['cuisine'];
// Get all cuisines list by get_terms() function.Its built in wordpress
$restaurant_cuisines = get_terms('cuisine', array('hide_empty' => false));
$cuisines = array();
foreach ($restaurant_cuisines as $restaurant_cuisine) {
// echo $restaurant_cuisine;
array_push( $cuisines, $restaurant_cuisine->slug );
// echo $cuisines_list;
}
print_r ($selected_cuisine);
print_r($cuisines);
if(array_intersect($selected_cuisine, $cuisines)){
$selected = 'selected';
}else{
$selected = '';
}
foreach ($restaurant_cuisines as $cuisine) {
echo '<option value="'. $cuisine->slug .'" '. $selected .' >'. $cuisine->name .'</option>';
}
?>
</select>
But the problem is that every options is getting selected.Actually there is total 3 cuisines : indian, thai & chainese and 2 of them are selected -> indian and thai.But problem is 3 options are selected. :/
Remember when you are using array_intersect it is setting true is at least one match in both array.So everything is getting selected.Rather you can try this:
<select name="cuisine[]" class="selectpicker show-tick form-control" data-selected-text-format="count > 3" data-done-button="true" data-done-button-text="OK" multiple>
<?php
$selected_cuisine = $_GET['cuisine'];
// Get all cuisines list by get_terms() function.Its built in wordpress
$restaurant_cuisines = get_terms('cuisine', array('hide_empty' => false));
$cuisines = array();
foreach ($restaurant_cuisines as $restaurant_cuisine) {
array_push( $cuisines, $restaurant_cuisine->slug );
}
foreach ($restaurant_cuisines as $cuisine) {
if(in_array($cuisine->slug, $selected_cuisine)){
$selected = 'selected';
}else{
$selected = '';
}
echo '<option value="'. $cuisine->slug .'" '. $selected .' >'. $cuisine->name .'</option>';
}
?>
I am trying to echo out "selected" on a value inside my array, within a foreach. If the form is false and my customer has already entered a particular value in my select, return it so he doesn't fill it again! That's what I am trying to do...
<?php
$marques = array('Word','Word1','Word20','Word46','Word9797');
foreach ($marques as $marque => $value)
{
if (isset($_POST['marque']) && $_POST['marque'] == $value[$_POST['marque']]) {
echo '<option value="'.$_POST["marque"].'">'.$value[$_POST["marque"]].'</option>';
}
echo '<option value="'.$marque.'">'.$value.'</option>';
}
?>
<?php
$marques = array('Word', 'Word1', 'Word20', 'Word46', 'Word9797');
foreach ($marques as $marque)
echo '<option value="'.$marque.'" '.(($marque == $_POST['marque']) ? 'selected' : '').'>'.$marque.'</option>';
?>
You mean this?
<?php
$marques = array('Word','Word1','Word20','Word46','Word9797');
foreach ($marques as $marque => $value) {
$setItSelected = '';
if (isset($_POST['marque']) && $_POST['marque'] == $marque) {
$setItSelected = 'selected';
}
echo '<option value="'.$marque.'" '.$setItSelected.'>'.$value.'</option>';
}
?>
Changing what's inside the value attribute doesn't make the item more or less selected. You need to add the selected attribute, see http://www.w3schools.com/tags/att_option_selected.asp
The output:ed html should look something like:
<option value="id" selected>some text</option>
<?php
$marques = array('Word','Word1','Word20','Word46','Word9797');
foreach ($marques as $marque)
{
if (isset($_POST['marque']) && $_POST['marque'] == $marque')
echo '<option value="'.$marque.'" selected>'.$marque.'</option>';
else
echo '<option value="'.$marque.'">'.$marque.'</option>';
}
?>
Your Array is one dimension, you can't use "=>"
For select option you must add the "selected" attribute too at your option tag
I have a dropdown box that holds the days 1-31 and i want to store/save what the user has previously selected if they return to the page.
My function to generate the box is:
public function fetchDDMMYYYYDropdown($select_d,$session_d) {
$days = range (1, 31);
$dropdown .= '<select name="'.$select_d.'">';
foreach($days as $key=>$name){
if($session_d==$name){
$session = 'selected';
}
$dropdown .= '<option value="'.sprintf("%02d", $name).'" selected="'.$session.'">'.sprintf("%02d", $name).'</option>';
}
$dropdown .= '</select>';
return $dropdown;
}
And my form is on this page:
<?php
session_start();
include("includes/func.class.php");
$dob = $func->fetchDDMMYYYYDropdown('dob_d', $_SESSION['dob_d']);
?>
<form action="t35t_send.php" method="get">
<?php echo $dob;?>
<input type="submit" value="send">
</form>
And it goes to this to save the SESSION variable:
session_start();
$_SESSION['dob_d'] = $_GET['dob_d'];
$dob = $_SESSION['dob_d'];
echo $dob;
I can tell that the $_SESSION['dob_d'] is correct and saved as i can output it inside both the function and the initial form page - so it's just the following which must not be right but at the moment the dropdown box just resets back to the first value, not the saved session:
if($session_d==$name){
$session = 'selected';
}
$dropdown .= '<option value="'.sprintf("%02d", $name).'" selected="'.$session.'">'.sprintf("%02d", $name).'</option>';
try this
function fetchDDMMYYYYDropdown($select_d,$session_d) {
$days = range (1, 31);
$dropdown .= '<select name="'.$select_d.'">';
foreach($days as $key=>$name){
if($session_d==$name){
$session = 'selected = selected';
}
else
{
$session = '';
}
$dropdown .= '<option value="'.sprintf("%02d", $name).'"'.$session.'">'.sprintf("%02d", $name).'</option>';
}
$dropdown .= '</select>';
return $dropdown;
}
The Problem was if even 'selected' is there in "option" even then value gets selected and in your previous code .. 'selected will be there for every date .. so it eas showing '31'.
I have changed the code so that 'selected = selected ' gets echo for the saved value.
Hope it helps you
A rough guess your if condition is not returning true,
Try checking the value of both variables.
Just to confirm can you replace the code as below and try.
if($session_d == sprintf("%02d", $name)){
$session = 'selected';
}
$dropdown .= '<option value="'.sprintf("%02d", $name).'" selected="'.$session.'">'.sprintf("%02d", $name).'</option>';
Using select and option HTML tags, I pass information through using $_POST.
When reloading the page however, the select resets back to the original values.
I am looking to get it to remember what has been passed through.
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo"<option value='$value-$first-$second'>$title - $first - $second</option>";
}
}
}
?>
As you can see, I use 3 foreach loops to populate whats in it.
How can I achieve my selection being remembered?
Thanks for reading.
You'll need to use the name of your select field in place of "your_select_field_name" in my change below:
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo "<option value='$value-$first-$second'";
if( $_POST['your_select_field_name'] == "$value-$first-$second" ) {
echo ' selected="selected"';
}
echo ">$title - $first - $second</option>";
}
}
}
?>
The output for the selected option on the new page needs to look like:
<option value='foo' selected>...<option>
HTML does not have memory. The item that's selected by default in a <select> form element is the one with the selected attribute (or the first one if none). Simply use the information contained in $_POST to generate the appropriate markup:
<select name="foo">
<option value="v1">Label 1</option>
<option value="v2">Label 2</option>
<option value="v2" selected="selected">Label 3</option>
<option value="v4">Label 4</option>
</select>
You need to set the selected tag on the correct option. Something like this:
<?php
$postedValue = $_POST['select_name'];
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
$computedValue = $value . '-' . $first . '-'. $second;
if ( $computedValue == $postedValue) {
$selected = "selected";
} else {
$selected = ''
}
echo "<option value='$computedValue' $selected>$title - $first - $second</option>";
}
}
}
?>
It could probably be written cleaner but this is the general idea.