Repopulating Select form fields in CodeIgniter - validation

I want to re-populate (i.e refill) values posted from a select form field after validation. I know codeigniter user guide proposed using set_select() function but their example from the guide assume you've hard-coded (in HTML) the array of values for the 'select' form element. In my case I used the Form Helper and my select field values are pulled from an array() like so:
$allstates = array('blah','blah2','blah3','blah4','blah5');
echo form_label('Select State Affiliate', 'state');
echo form_dropdown('state', $allstates);
Needless to say, $allstates array is dynamic and changes over time. So how do I code such that my select field can be re-populated with the value the user selected?

You can set the value that should be preselected via the third paramater of form_dropdown. The value that the user selected in the previous step is in $this->input->post('state'). So you would use:
echo form_dropdown('state', $allstates, $this->input->post('state'));
From the user guide:
The first parameter will contain the name of the field, the second parameter will contain an associative array of options, and the third parameter will contain the value you wish to be selected
$options = array(
'small' => 'Small Shirt',
'med' => 'Medium Shirt',
'large' => 'Large Shirt',
'xlarge' => 'Extra Large Shirt',
);
$shirts_on_sale = array('small', 'large');
echo form_dropdown('shirts', $options, 'large');
// Would produce:
<select name="shirts">
<option value="small">Small Shirt</option>
<option value="med">Medium Shirt</option>
<option value="large" selected="selected">Large Shirt</option>
<option value="xlarge">Extra Large Shirt</option>
</select>

Sometimes, especially when working with objects, it might be easier to do this without the form helper:
<select name="my_select>
<?php foreach ( $my_object_with_data as $row ): ?>
<option value="" <?php if ( isset( $current_item->title ) AND $row->title == $current_item->title ) { echo 'selected="selected"';} ?> >
<?php echo $row->title; ?>
</option>
<?php endforeach; ?>
</select>
I know it's very ugly, but in a lot of cases this was the easiest way of doing it when working with objects instead of an associative array.

Related

codeigniter form_dropdown return wrong value

My Model,
function get_partners_name()
{
$q = $this->db->select("id,fname,lname")
->from('partner');
$all_partners = $q->get()->result();
$data = array();
foreach($all_partners as $partner)
{
$data[$partner->id] = $partner->fname.' '.$partner->lname;
}
return $data;
}
my controller var_dump($partners) data is,
array (size=2)
38 => string 'Mahesh' (length=6)
40 => string 'Rahul' (length=4)
My view,
<?php array_unshift($partners, "-Select-");?>
<?php echo form_dropdown('parnter', $partners,'',''); ?>
so in dropdown i want to display,
<option value='0'>-Select-</option>
<option value='38'>Mahesh</option>
<option value='40'>Rahul</option>
But it display,
<option value='0'>-Select-</option>
<option value='1'>Mahesh</option>
<option value='2'>Rahul</option>
from the PHP manual.
'array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.'
so your keys are being renumbered when using unshift.
since the select option should never be selected I would suggest hardcoding it into the view. also don't give it a value if you don't want users to select it.
<select name='foo'>
<option disabled>-Select-</option>
<?php
foreach($partners as $partner){
echo '<option value="';
echo $partner->id;
echo '">';
echo $partner->name;
echo '</option>';
}
?>
</select>

Dependanat Drop down is not working when it has only one value in yii framework

I am using dependant dropdownlist for get value for subject dropdown when select value from 'Grade' dropdown. It is working fine. But the problem is when there are only one value in grade dropdown the subject dropdown is not updated.
this is my code:-
Grade DropDown----------
($data is consist of grade)
<?php echo CHtml::dropDownList('myDropDown1','',$data,array(
'id'=>'gr',
'empty' => '(Select Grade)',
'style'=>'width:200px',
'ajax' =>
array(
'type'=>'POST', //request type
'url'=>CController::createUrl('sub'), //action to call
'update'=>'#cls', // which HTML element to update
)
)); ?>
Subject Dropdown (which depend on grade dropdown)------------
<?php echo CHtml::label('Subject',''); ?>
<?php echo CHtml::dropDownList('myDropDown3','',array(),array(
'id'=>'sub',
'prompt'=> 'Please select a class', 'style'=>'width:150px',
'style'=>'width:200px',
)); ?>
<?php //echo $form->error($model,'sub_id'); ?>
In controller-------------------
public function actionClass()
{
$grd = $_POST['myDropDown1'];
$c_id = TbClass::model()->findAll('id=:id',
array(':id'=>$grd,));
$data3 = CHtml::listData($c_id,'id','grade');
$grd2 = array_shift($data3);
$sub1 = TbClass::model()->findAll('grade=:grade',
array(
':grade'=>$grd2,
));
$data4 = CHtml::listData($sub1,'id','class');
foreach($data4 as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
This code is working fine. Problem is when grade has only one value in the dropdown , cannot update the subject dropdown.
I think your problem is in array_shift,
have you checked the value of $grd2 ?

Codeigniter: Using set_select() if dropdown data comes from the db

I have a dropdown <select> field which gets its values from the db. I'm currently looking for a way to use set_select() but have been unsuccessful. Here's my existing view:
<select name="userbase">
<?php echo $userbase_list; ?>
</select>
The variable $userbase_list is a string containing all the <option value="">text</option> html to be inserted. Since this <select> is generated from the db, does that mean I can't use the CI set_select() anymore?
$array_of_options= array("key_one"=>"val_one", "key_two"=>"val_two");
foreach($array_of_options as $k => $v)
{
$selected = ($v === $db_result) ? 'selected=selected' : '';
echo '<option '.$selected.' value='.$k.'>' . $v . '</option>';
}

Combining date and time input data into one field with WPAlchemy metaboxes

I'm trying to convert a metabox for date and time I'm currently using into a WPAlchemy metabox.
I am currently combining the start date and start time into one field upon save.
This is the old save function:
add_action ('save_post', 'save_event');
function save_event(){
global $post;
// - still require nonce
if ( !wp_verify_nonce( $_POST['event-nonce'], 'event-nonce' )) {
return $post->ID;
}
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
// - convert back to unix & update post
if(!isset($_POST["startdate"])):
return $post;
endif;
$updatestartd = strtotime ( $_POST["startdate"] . $_POST["starttime"] );
update_post_meta($post->ID, "startdate", $updatestartd );
if(!isset($_POST["enddate"])):
return $post;
endif;
$updateendd = strtotime ( $_POST["enddate"] . $_POST["endtime"]);
update_post_meta($post->ID, "enddate", $updateendd );
Here are the new functions and fields for reference:
$custom_event_metabox = new WPAlchemy_MetaBox(array
(
'id' => '_custom_event_meta',
'title' => 'Event Information',
'template' => /event_meta.php',
'types' => array('event'),
'context' => 'normal',
'priority' => 'high',
'mode' => WPALCHEMY_MODE_EXTRACT,
'save_filter' => 'event_save_filter',
'prefix' => '_my_' // defaults to NULL
));
<li><label>Start Date</label>
<?php $mb->the_field('startdate'); ?>
<input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" class="tsadate" />
</li>
<li><label>Start Time</label>
<?php $mb->the_field('starttime'); ?>
<input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" class="tsatime" />
<span><em>Use 24h format (7pm = 19:00)</em></span>
</li>
<li><label>End Date</label>
<?php $mb->the_field('enddate'); ?>
<input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" class="tsadate" />
</li>
<li><label>End Time</label>
<?php $mb->the_field('endtime'); ?>
<input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" class="tsatime" />
<span><em>Use 24h format (7pm = 19:00)</em></span>
The issue I'm facing is I'm not entirely sure if I should be using the save_filter or the save_action, or how I should handle doing this ala WPAlchemy.
This is what I have thus far:
function event_save_filter($meta, $post_id)
{
// the meta array which can be minipulated
var_dump($meta);
// the current post id
var_dump($post_id);
// fix: remove exit, exit here only to show you the output when saving
//exit;
// - convert back to unix & update post
if(!isset($_POST["startdate"])):
return $post;
endif;
$updatestartd = strtotime ( $_POST["startdate"] . $_POST["starttime"] );
update_post_meta($post->ID, "startdate", $updatestartd );
if(!isset($_POST["enddate"])):
return $post;
endif;
$updateendd = strtotime ( $_POST["enddate"] . $_POST["endtime"]);
update_post_meta($post->ID, "enddate", $updateendd );
// filters must always continue the chain and return the data (passing it through the filter)
return $meta;
}
Will this work? And should it be a save_filter or a save_action?
Any insight appreciated ;-)
If you are using WPAlchemy, and all you need is to add new values or update values in your meta data. You can achieve this by adding additional values to the $meta array. When you return it as you should always do when using the save_filter, WPAlchemy will handle the saving of the data.
The main difference between save_filter vs save_action is that with the filter, you must pass back the $meta value, but you can modify the array before doing so, which allows you to save hidden values.
The power in using any of these options is that you can manipulate other aspects of WordPress during a post update and per the values that a user enters in.
Passing back false in the save_filter tells WPAlchemy to stop and not save. An additional difference between the two is also that save_filter happens before the save and save_action happens afterwards.
Here is my attempt at adjusting your code above, obviously you will have to touch it up to make it work for you, please read the comments I've included.
function event_save_filter($meta, $post_id)
{
// the meta array which can be minipulated
var_dump($meta);
// the current post id
var_dump($post_id);
// fix: remove exit, exit here only to show you the output when saving
//exit;
// at this time WPAlchemy does not have any field validation
// it is best to handle validation with JS prior to form submit
// If you are going to handle validation here, then you should
// probably handle it up front before saving anything
if( ! isset($meta['startdate']) OR ! isset($meta['enddate']))
{
// returning false stops WPAlchemy from saving
return false;
}
$updatestartd = strtotime($meta['startdate'] . $meta['starttime']);
// this is an example of setting an additional meta value
$meta['startdate_ts'] = $updatestartd;
// important:
// you may or may not need the following, at this time,
// WPAlchemy saves its data as an array in wp_postmeta,
// this is good or bad depending on the task at hand, if
// you need to use query_post() WP function with the "startdate"
// parameter, your best bet is to set the following meta value
// outside of the WPAlchemy context.
update_post_meta($post_id, "startdate", $updatestartd );
$updateendd = strtotime ($meta['enddate'] . $meta['endtime']);
// similar note applies
update_post_meta($post_id, "enddate", $updateendd );
// filters must always continue the chain and return the data (passing it through the filter)
return $meta;
}

CodeIgniter function for returning special dropdown

I want to create a function in my model that does something a bit different and need a bit of help.
I have a database table with names, description, ids etc etc .... there is only one of each name, but i want to return 3 entries for every 1 name, prefixed with a number on it.
So, for example, if i have 2 entries in my database with the names 'joe' and 'bob' .... i want my dropdown box to look like the following
<select>
<option value="joe1">joe1 - description</value>
<option value="joe2">joe2 - description</value>
<option value="joe3">joe3 - description</value>
<option value="bob1">bob1 - description</value>
<option value="bob2">bob2 - description</value>
<option value="bob3">bob3 - description</value>
and so on for additional entries in the DB.
i understand how to do a normal dropdown box, but not one like this.
Any help would be grand :)
Try something like this:
function get_users()
{
$this->db->select("id,name,desc");
$this->db->from("table_name");
$q = $this->db->get();
$rows = $q->row_array();
}
In controller method:
$data = array();
$data['users'] = $this->model_name->get_users();
$this->load->view('view_name',$data);
In view:
<?php
echo "<SELECT>";
foreach($users as $user)
{
for ($i=1; $i<=3; $i++)
{
$id = $user['id'].$i;
echo '<option value="'.$id.'">'.$id.' - '.$user['desc'].'</option>';
}
}
echo "</SELECT>";
?>

Resources