简体   繁体   中英

Validation error message doesn't appear in View?

My $msg doesn't appear in the view when the user's input is invalid. No error show, just that the error msg doesn't appear. Below is my controller and view.

Login controller

public function index($msg = null){
    $data['msg'] = $msg;
    $this->load->view('login_view', $data);
}

public function process(){
    $this->load->model('login_model');

    $result = $this->login_model->validate();

    if(!$result){
        $msg = '<font color=red>Invalid username and/or password.</font><br />';
        $this->index();
    }else{
        // if validated to member area
        redirect('home');
    }
}

my login_view

<?php if(! is_null($msg)) echo $msg;?>

the $this->index works but the $msg is always null , I wonder why.

public function index($msg = null){

    $data['msg'] = $msg;
    $this->load->view('login_view', $data);
}

public function process(){
    $this->load->model('login_model');

    $result = $this->login_model->validate();

    if(!$result){
        $msg = '<font color=red>Invalid username and/or password.</font><br />';
        $this->index($msg);
    }else{
        // if validated to member area
        redirect('home');
    }
}

You need to pass the variable , since it is not in scope of that other function - i am going to create another answer with another way to do this another way as an example. -- try to keep HTML out of the controller if you can .

protected $viewData = array(); 

public function __construct(){
    parent::__construct(); 
}

public function index(){
    $this->load->view('login_view', $this->viewData);
}

public function process(){
    $this->load->model('login_model');

    if(!$result = $this->login_model->validate()){
        $this->viewData['msg'] = array(
            'msg' => 'Put your message Here',
            'class' => 'error'
        );
        return $this->index();
    }
    redirect('home');
}

////////////////////////////////////////////

view file

<?php 

    if(isset($msg['msg'], $msg['class'])){ 

        echo '<span class="'.$msg['class'].'" >' .  $msg['msg'] . '</span>';

    }

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM