If you happened to work with the ‘form_validation’ library and dropdown lists, and had to populate the default value from database, I am sure you would have come across this issue too. I’ve been having this issue for the past couple of days and found a workaround to tackle the issue. Thought this would help you too in your projects.
Note: At this point the dropdown should populate with all the values but it should select NOT its default value but the selection user made before they submitted.
Example
//Controller
$this->load->library(‘form_validation’);
$this->load->helper(‘form_helper’);
$this->form_validation->set_rules(‘states’, ‘State’, ‘required|trim’);
if ($this->form_validation->run() == TRUE) {
…
}//Model
function get_states($mode = false,$content){
$this->db->select(‘abv, states’);
$this->db->order_by(“states”, “asc”);
$q = $this->db->get(‘states’);
if($mode){
$data[‘ ‘] = $content;
}
foreach ($q->result_array() as $row) {
$data{$row[‘abv’]} = $row[‘status’];
}
return $data;
}
//View
// Workaround function which will swap the default value
function set_my_defaults($item,$default) {
if(set_value($item)!=””){
return set_value($item);
}
else {
return $default;
}
}$this->load->model(‘my_model’);
$default = ‘NY’ ; // Initial default value you get from a database or hard code
$states = $this->my_model->get_states(true,’Please Select’);
$selected = set_my_defaults(‘state’,$default);
echo form_dropdown(‘state’,$states,$selected,’class=”dropdown_style”‘);
Hope this will work for you too. If you find a better way to implement this or have any question please feel free to leave a comment.
Comments are closed.
What we have to include in this..????? plss let me know.
if ($this->form_validation->run() == TRUE)
{
…
}
Well.. That section will be executed if you have a successful form submission.
As an example you can have something like this;
if ($this->form_validation->run() == TRUE)
{
$data = array( ‘states’ => $this->input->post( ‘states’));
$id = $this->session->userdata(‘UserID);
$this->db->where(‘id’, $id);
$this->db->update(‘users’, $data);
}
Hmh, can you help me if i want some static word into dropdown like a name of category and than you can chose betwen items in categorys?