0

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 class="form-group">
  <label for="" class="control-label"> Category</label>
  <select name="category_id" id="category" class="custom-select select">
    <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 class="form-group">
  <label for="" class="control-label">Sub Category</label>
  <select name="sub_category_id" id="subcategory" class="custom-select select">
    <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

2
  • Could you show the get_subcategory method in your admin controller? Commented May 22, 2022 at 14:43
  • function get_subcategory() { if ($this->input->post('parent_id')) { echo $this->Admin_model->get_subcategory($this->input->post('parent_id')); } } this is the get_subcategory method Commented May 22, 2022 at 14:54

1 Answer 1

1

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>';
      }
    }
  }
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks a lot! This method gets all the subcategories in the database but, how should I get just the subcategories of that selected category?
Since you're passing along the parent_id, this should only return the subcategories for the category with the given parent_id. On which page (insert/edit) are you seeing all the subcategories in the database being loaded, and does that happen when the page first loads, or only when changing the category select?
That method is getting all the subcategories and not filtering by parent_id. You need to use Admin_model->sub_category(...) in the get_subcategory method in the controller. Updated my answer.
As for the undefined variable error you posted earlier, use if (isset($products)) { ... } to check if the variable exists before using it.
In insert_product(), replace $data['subcategory'] = $this->Admin_model->get_subcategory(); with $data['subcategory'] = [];, to not pass any subcategories to the view. JavaScript will load them if the category select changes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.