Welcome Guest, Not a member yet? Register   Sign In
Dynamic dependant dropdown from database
#5

(12-26-2015, 08:58 AM)GingerNut Wrote: I desperately need a dynamic dependant dropdown from database.

Hey, there. I just implemented that. Check out my Search Scraper application on GitHub. The basic idea is this. In your controller, load from the database the values that will populate the dropdown, and then pass those values to your view, which will then use them when building the dropdown. In my controller's constructor, I do this:
PHP Code:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class 
Searches extends CI_Controller {

protected 
$sites = array();
protected 
$searches = array();

    public function 
__construct()
    {
        
parent::__construct();
        
$this->load->helper('url');
        
$this->load->helper('download');
        
$this->load->library('form_validation');
        
$this->load->library('table');
        
$this->load->model('searches_model');
        
$this->sites $this->searches_model->get_sites(); // loading dropdown values from database
        
$this->load->driver('site'array_column($this->sites'class'));
        
$this->searches $this->searches_model->get_searches();
    } 


The call to get_sites() in my model executes this code:
PHP Code:
public function get_sites()
{
 
   return $this->db->query(
 
       'SELECT
            sites.id AS id,
            sites.name AS name
         FROM sites;'
 
   )->result_array();




Now that I have the array $sites holding the sites I have in the database, I pass it to the view:
PHP Code:
$data = array(
    
'subview' => 'search_add_view',
    
'sites' => $this->sites,
    
'searches' => $this->searches
);
$this->load->view('searches_view'$data); 

And then my view goes and does this:

PHP Code:
<select id="sites" name="search[site_id]">
 
   <option value="" selected>Select one</option>
 
   <?php foreach ($sites as $row):?>
        <option value="<?php echo $row['id']?>"><?php echo $row['name']?></option>
    <?php endforeach;?>
</select> 

I hope that's a good example, but if it's not clear, please let me know where it derails. Good Luck!
Hey, don't work without a PHP debugger. Several free IDEs have this features built in. Two are NetBeans and CodeLobster. Without a debugger, it's like you're driving with a blindfold on -- you are going to crash!
Reply


Messages In This Thread
RE: Dynamic dependant dropdown from database - by RobertSF - 12-26-2015, 04:29 PM



Theme © iAndrew 2016 - Forum software by © MyBB