Home > Enterprise >  Dependent dropdown, second dropdown not populated, Codeigniter
Dependent dropdown, second dropdown not populated, Codeigniter

Time:05-23

I have a dependent drop down that get the category on the first drop down and should get the subcategory on the second drop down but the subcategory drop down isn't populated. I have something like this in my Model:

public function category()
{
    $response = array();

    $this->search(array(), 'date_created');

    $this->db->select('*');
    $query = $this->db->get('categories');
    $response = $query->result_array();

    return $response;
}
public function sub_category($parent_id)
{
    $query = $this->db->get_where('sub_categories', array('parent_id' => $parent_id));

    return $query->result_array();
}

And then something like this on my Controller:

public function edit_product($id)
{
    $data['title'] = 'Update Product';

    $this->load->view('../admin/template/admin_header');
    $products = new Admin_model;
    $data['products'] = $products->edit_product($id);
    $data['category'] = $this->Admin_model->category();
    $data['subcategory'] = $this->Admin_model->sub_category($data['products']->category_id);
    $this->load->view('../admin/template/admin_topnav');
    $this->load->view('../admin/template/admin_sidebar');
    $this->load->view('../admin/products/manage_product', $data);
    $this->load->view('../admin/template/admin_footer');
}

function get_subcategory()
{
    if ($this->input->post('parent_id')) {
        echo $this->Admin_model->get_subcategory($this->input->post('parent_id'));
    }
}
public function insert_product()
{
    $productData = array();

    if ($this->input->post('productData')) {
        $this->form_validation->set_rules('category_id', 'Category', 'required');
        $this->form_validation->set_rules('sub_category_id', 'Sub Category', 'required');
        $this->form_validation->set_rules('product_name', 'Product Name', 'required');
        $this->form_validation->set_rules('department', 'Department', 'required');
        $this->form_validation->set_rules('description', 'Description', 'trim|required');
        $this->form_validation->set_rules('status', 'Status', 'required');

        if ($this->form_validation->run() == true) {
            $ori_filename = $_FILES['product_image']['name'];
            $update_image = time() . "" . str_replace(' ', '-', $ori_filename);
            $config = [
                'upload_path' => './images/products',
                'allowed_types' => 'gif|jpg|png',
                'file_name' => $update_image,
            ];

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('product_image')) {
                $error = array('error' => $this->upload->display_errors());
                $this->load->view(base_url('admin/products'), $error);
            } else {

                $image = $this->upload->data('file_name');
                $productData = array(
                    'category_id' => $this->input->post('category_id'),
                    'sub_category_id' => $this->input->post('sub_category_id'),
                    'product_name' => $this->input->post('product_name'),
                    'department' => $this->input->post('department'),
                    'description' => $this->input->post(htmlentities('description')),
                    'status' => $this->input->post('status'),
                    'upload_path' => $image
                );
                $img = new Admin_model;
                $img->insert_product($productData);
                $this->session->set_flashdata('status', 'Package InsertedSuccesfully');
                redirect(base_url('admin/products'));
            }
        }
    }

    $data['title'] = 'Insert Product';
    $data['category'] = $this->Admin_model->category();
    $data['subcategory'] = $this->Admin_model->get_subcategory();

    $this->load->view('../admin/template/admin_header');
    $this->load->view('../admin/template/admin_topnav');
    $this->load->view('../admin/template/admin_sidebar');
    $this->load->view('../admin/products/manage_product', $data);
    $this->load->view('../admin/template/admin_footer');
}

And then the view:

    <div >
  <label for="" > Category</label>
  <select name="category_id" id="category" >
    <option value="">Select Category</option>
    <?php
       foreach ($category as $row) {
             echo '<option value="' . $row['id'] . '"';
             if (isset($products) && $row['id'] == $products->category_id) {
                  echo ' selected';
             }
                echo '>' . $row['category'] . '</option>';
             }
   ?>
    </select>
</div>
<div >
  <label for="" >Sub Category</label>
  <select name="sub_category_id" id="subcategory" >
    <option value="">Select Sub Category</option>
    <?php
      foreach ($subcategory as $row) {
          echo '<option value="' . $row['id'] . '"';
          if ($row['id'] == $products->sub_category_id) {
              echo ' selected';
          }
              echo '>' . $row['sub_category'] . '</option>';
         }
    ?>
  </select>
</div>

And here's the script. I'm not really familiar at AJAX so i tried to ask and get answers here which helps me progress but I still can't populate the subcategory drop down.

<script type="text/javascript">
$(document).ready(function() {

    $('#category').change(function() {
        var parent_id = $('#category').val();
        console.log(parent_id)
        if (parent_id != '') {
            $.ajax({
                url: "<?php echo base_url(); ?>admin/get_subcategory",
                method: "POST",
                data: {
                    parent_id: parent_id
                },
                success: function(data) {
                    $('#subcategory').html(data);
                    console.log(data)
                }
            });
        } else {
            $('#subcategory').html('<option value="">Select Category First</option>');
        }
    });
});

Also, here's what I get in the console enter image description here

CodePudding user response:

The result from $this->Admin_model->sub_category(...) is an array. echo works on string values only, which is why you're getting the error. You'll need to loop over the result array (in admin/get_subcategory) and print the values one by one. Also surround each value with an <option> tag so the result can be placed in the select box without further modification:

  public function get_subcategory() {
    if ($this->input->post('parent_id')) { 
      $subcategories = $this->Admin_model->sub_category($this->input->post('parent_id'));
      foreach ($subcategories as $subcategory) {
        echo '<option value="'.$subcategory['id'].'">'.$subcategory['sub_category'].'</option>';
      }
    }
  }
  • Related