Posted by Arjun on Wednesday 24th September 2014

CodeIgniter Helper :: Quick Dynamic DropDown Select Box ?

CI helper DropDown Helper Quick Dynamic DropDown

This post is about Quick and Easy Drop-down HTML Select box element generation with custom CI helper function(CI helper file merely contains your defined functions)

You might like this post -
How to create custom helper in CodeIgniter

Here is the steps to create Helper , just crate a file called dropdown_helper.php in application/helper/dropdown_helper.php. then copy paste the following code.

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

 
  function listData($table,$name,$value,$orderBy='ASC') {
	  $items = array();
	  $CI =& get_instance();
	  if($orderBy) {
		  $CI->db->order_by($value,$orderBy);
	  }
	  $query = $CI->db->select("$name,$value")->from($table)->get();
	  if ($query->num_rows() > 0) {
		  foreach($query->result() as $data) {
			  $items[$data->$name] = $data->$value;
		  }
		  $query->free_result();
		  return $items;
	  }
  }

/* End of file dropdwon_helper.php */
/* Location: ./application/helper/dropdown_helper.php */

How to use Dropdown helper?

To use this helper, you should load this helper just like ci core helpers,you can load this helper controller level or method level or you can set auto load in applications/config/autoload.php(you can use any were in the application).

  $this->load->helper('dropdown');

How to Use Show Me Example

Create a controller class called test.php in application/controllers/test.php, then copy past below script

<?php 
class Test extends CI_Controller {
	
	 public function index() {
		 $this->load->helper(array('dropdown','form'));
		 $dropdownItems = listData('country_tbl','country_id', 'country_name');
		 echo form_dropdown('dropdown',$dropdownItems,$selected = 8);
	 }
}

/* End of file test.php */
/* Location: ./application/controllers/test.php */