Code
Code

Reputation: 303

Displaying default values in codeigniter

In the home page, all subjects should be displayed. When the subject is clicked, their respective chapters has to be displayed. For the first time, that is when the subject is not choosen, then chapters of subject id 1 has to be displayed. In the below code, should i have to call get_chapters() from index and make get_chapters() to return chapters or any other better way of doing it?

class Home extends CI_Controller {

private $data = array();

public function index()
{       
    $this->load->model('subjects_model');
    if($query = $this->subjects_model->get_all()) {
        $data['subjects'] = $query->result_array();
    }       


    $this->load->view('home_view', $data);
}



public function get_chapters($id=null) {

    $this->load->model("chapters_model");

    if(!is_null($id)) {
        $query = $this->chapters_model->get_where('chapters', array('subject_id'=>$id));
    } else {
        $query = $this->chapters_model->get('chapters');
    }

    if($query) {
        $data['chapters'] = $query->result_array();
    }

    $this->load->view('home_view', $data);      
}

}

Upvotes: 1

Views: 55

Answers (2)

Sachin Aghera
Sachin Aghera

Reputation: 506

public function index($id=null) 

{

        $this->load->model("chapters_model");

        if(is_null($id)) {
             $id = 1;   
         }

        $query = $this->chapters_model->get_where('chapters', array('subject_id'=>$id));

        if($query) {
            $data['chapters'] = $query->result_array();
         }

        $this->load->view('home_view', $data);
}

Upvotes: 0

GautamD31
GautamD31

Reputation: 28763

Try like

public function get_chapters($id=null) {
    $this->load->model("chapters_model");

    if(is_null($id)) {
        $id = 1;   
    }
    $query = $this->chapters_model->get_where('chapters', array('subject_id'=>$id));

    if($query) {
        $data['chapters'] = $query->result_array();
    }

    $this->load->view('home_view', $data);
}

If the $id is null then defaltly subject id will become 1 orelse it will search with the existing subject id

Upvotes: 2

Related Questions