Chain select with category and sub category in CodeIgniter

后端 未结 3 1366
别那么骄傲
别那么骄傲 2020-12-22 02:47

How to create a dropdown select menu in CI so that if I select a category, a sub category will appear on the same page without refreshing the browser?

3条回答
  •  没有蜡笔的小新
    2020-12-22 03:12

    This is how I've done it, (very easy to do)

    1. download jQuery, + jquery.chained.js
    2. insert jQuery + jquery.chained.js to the CI view(s)
    3. create function for generating selects from database
    4. calling the function

    as far my structure of tables is as following (I know it can be easily done in one table)

    category

    CREATE TABLE IF NOT EXISTS `category` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(64) NOT NULL,
      `active` tinyint(1) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;
    
    INSERT INTO `category` (`id`, `name`, `active`) VALUES
    (3, 'Science', 1),
    (4, 'History', 1);
    

    subcategory

    CREATE TABLE IF NOT EXISTS `subcategory` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `category_id` int(11) NOT NULL,
      `name` varchar(64) NOT NULL,
      `active` int(11) NOT NULL,
      PRIMARY KEY (`id`),
      KEY `category_id` (`category_id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;
    
    INSERT INTO `subcategory` (`id`, `category_id`, `name`, `active`) VALUES
    (2, 3, 'Mathematics', 1),
    (3, 3, 'Physics', 1),
    (4, 3, 'Medicine', 1),
    (5, 4, '21st Century', 1),
    (6, 4, '18-20th Century', 1),
    (7, 4, '15-17th Century', 1),
    (8, 4, 'Before 15th Century', 1);
    
    ALTER TABLE `subcategory`
      ADD CONSTRAINT `subcategory_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`);
    

    Now I just load all the active categories/subcategories and create "; $return .= ""; foreach ($categories as $category) { $return .= ""; } $return .= ""; $return .= "

"; $return .= "
"; $return .= ""; $return .= "
"; $this->data['category_chain'] = $return; }

lastly create application/models/general_model.php and create this function

function _getAllWhere($table, $where, $value) { 
        $q = $this->db->get_where($table, array($where => $value)); 
        return ($q->num_rows() > 0) ? $q->result() : FALSE; 
} 

Lasts step is to call the function in a way that it is called just when we need it. In desired controller just call $this->category_chain() and in view there will be a variable avalible $category_chain (just echo it out like )

Thats it ;)

提交回复
热议问题