How to load a view based on condition in Controlle

2019-02-25 07:06发布

问题:

I'm new to codeigniter. I'm trying to make a simple site, that will get its "settings" on the database, if the site is enabled (1) or not (0).

I'm trying to determine the site settings if enabled (1) or not (0) and display the index view (if site value == 1)

and maintenance view (if site value is == 0 or null)


I have written the code already and I can echo the "site" value in a view.

Model

function getsetting() {
$this->db->select("site");
$this->db->from('configuration');
$query = $this->db->get();
$ret = $query->row();
return $ret->site;
}

Controller

    //if site value is == 1 load the normal view
    $this->load->view('index', $data);
    //else load the maintenance view
    $this->load->view('maintenance', $data)

I have a database "mysite" with one table "configuration" and one column "site" the values [null or 1] are from site column, for determining what view should be displayed.




Any help is accepted. Thanks in advance.

回答1:

MODEL Here you need to fetch single row by using $query->row(); and pass it to controller

function getsetting() {
$this->db->select("site");
$this->db->from('configuration');
$query = $this->db->get();
$ret = $query->row();
return $ret->site;
}

As you describe in your question

the values [null or 1]

Controller

function your_controler() {

        $this->load->model('model_file');

        $site = $this->model_file->getsetting();
        if(isset($site) && $site==1){// your condition here
        $this->load->view('index', $data);
        }else{
            $this->load->view('maintenance', $data)

        }

    }


回答2:

Use something like this for your controller:

$setting = $this->modelName->getsetting();

if($setting['maintenance'] == 1){

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

} else {

     $this->load->view('index' $data);

}

Be sure to replace 'modelName' with the name of the 'getsetting' method's model.



回答3:

If you want to disable all method access in maintenance mode, do something like below in your controller's constructor,

public function __construct()
{
    parent::__construct();
    $site = $this->Datamodel->getsetting();
    if(isset($site->site) && $site->site==1)
    {
        $this->load->view('index');
        die;
    }
}