codeigniter Invalid argument supplied for foreach() - codeigniter

I have a full working code with retrieve insert update and delete data to database.
All is working well, but if I delete some data, it is deleted but when direct to my view page again, then it will return "Invalid argument supplied for foreach()".
When I press again my view page link it is all normal and the data I delete is gone too, this is just happen with delete function.
Code :
Controller :
public function merk(){
//$data["result"] = $this->modelAdminMerk->getMerk();
$data["totalRows"] = $this->modelAdminMerk->getTotalRows();
$config["base_url"] = base_url() . "admin/merk";
$config["per_page"] = 15;
$config["total_rows"] = $data["totalRows"];
$config["uri_segment"] = 3;
$config["num_links"] = 10;
$this->pagination->initialize($config);
if( ! $this->uri->segment(3)){
$page = 0;
}else{
$page = $this->uri->segment(3);
}
$data["results"] = $this->modelAdminMerk->getMerkByPages($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view("adminView/adminHeader");
$this->load->view("adminView/adminMerk", $data);
$this->load->view("adminView/adminFooter");
}
public function insertMerk(){
$this->load->view("adminView/adminHeader");
$this->load->view("adminView/adminInsertMerk");
$this->load->view("adminView/adminFooter");
}
public function validateInsertMerk(){
$this->form_validation->set_rules("namaMerk", "Nama Merk", "trim|required|min_length[3]|max_length[30]");
if($this->form_validation->run()){
$newMerk = array("merk" => $this->input->post("namaMerk"));
$this->modelAdminMerk->insertMerk($newMerk);
$this->merk();
}else{
echo "GAGAL!!!";
}
}
public function editMerk($id){
$data["merk"] = $this->modelAdminMerk->getMerkById($id);
$this->load->view("adminView/adminHeader");
$this->load->view("adminView/adminEditMerk", $data);
$this->load->view("adminView/adminFooter");
}
function validateEditMerk(){
$this->form_validation->set_rules("namaMerk", "Nama Merk", "trim|required|min_length[3]|max_length[30]");
if($this->form_validation->run()){
$newMerk = array("merk" => $this->input->post("namaMerk"));
$this->modelAdminMerk->editMerk($this->input->post("id"), $newMerk);
$this->merk();
}else{
echo "GAGAL";
}
}
public function deleteMerk($id){
$this->modelAdminMerk->deleteMerk($id);
$this->merk();
}
Model :
function getMerk(){
$data = $this->db->query("SELECT * FROM merkbarang");
return $data->result();
}
function getMerkById($id){
$this->db->where("id", $id);
$data = $this->db->get("merkbarang");
return $data->row();
}
function insertMerk($newMerk){
$this->db->insert("merkbarang", $newMerk);
return true;
}
function editMerk($id, $newMerk){
$this->db->where("id", $id);
$this->db->update("merkbarang", $newMerk);
return true;
}
function deleteMerk($id){
$this->db->where("id", $id);
$this->db->delete("merkbarang");
return true;
}
function getTotalRows(){
$rows = $this->db->count_all("merkbarang");
return $rows;
}
function getMerkByPages($limit, $start){
$this->db->limit($limit, $start);
$query = $this->db->get("merkbarang");
if($query->num_rows() > 0){
foreach ($query->result() as $row){
$data[] = $row;
}
return $data;
}else{
return false;
}
}
View :
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="panel panel-danger">
<div class="panel-body">
<ul class="nav nav-pills nav-stacked">
<li role="presentation" class="active">Insert Merk</li>
</ul>
</div>
</div>
</div>
<div class="col-md-9">
<div class="panel panel-default">
<div class="panel-heading">
<strong>Merk</strong>
</div>
<div class="panel-body">
<div class="row" id="tabelBarang">
<div class="col-md-1 colBarang">
<strong>No</strong>
</div>
<div class="col-md-7 colBarang">
<strong>Merk</strong>
</div>
<div class="col-md-4 colBarang">
<strong>Action</strong>
</div>
</div>
<?php
$angka = 0;
foreach ($results as $row){
$id = $row->id;
$merk = $row->merk;
?>
<div class="row" id="tabelBarang">
<div class="col-md-1 colBarang">
<?php echo ++$angka; ?>
</div>
<div class="col-md-7 colBarang">
<?php echo $merk; ?>
</div>
<div class="col-md-2 colBarang">
<button type="button" class="btn btn-info btn-xs" aria-label="Left Align">
Edit
</button>
</div>
<div class="col-md-2 colBarang">
<button type="button" class="btn btn-danger btn-xs" aria-label="Left Align">
Delete
</button>
</div>
</div>
<?php
}
?>
<?php echo $links; ?>
</div>
</div>
</div>
</div>
</div>

The way I see it, there is nothing wrong in your code, that should definitely work, but I would suggest you to try CI's redirect() method in your delete function
public function deleteMerk($id){
$this->modelAdminMerk->deleteMerk($id);
redirect('controllername/merk');
}

Related

gallery images does not get updated in database

I have an event management company website. https://redcarpetevents.in. the only issue is i cannot update the image gallery. i can upload new images, that works fine. but when i edit the images already in the database, it is not getting updated.
routes.php
Route::get('admin/editGalleryForm/{type}/{editId}', array('as'=>'editGalleryForm','before'=>'authAdmin','uses'=>'AdminController#editGalleryForm'));
Route::post('admin/editGallery', array('as'=>'editGallery','before'=>'csrf|xss_clean|authAdmin','uses'=>'FormController#editGallery'));
Model.php
public static function editGallery($data){
$gallery = Gallery::find($data['editId']);
$gallery->type = $data['type'];
$gallery->tag = $data['tag'];
$gallery->position = $data['order'];
if (isset($data['status'])) {
$gallery->status = $data['status'];
}else{
$gallery->status = 'off';
}
if (isset($data['home'])) {
$gallery->home = $data['home'];
}else{
$gallery->home = 'off';
}
if (isset($data['title'])) {
$gallery->title = $data['title'];
}
if($gallery->update()){
return true;
}else{
return false;
}
}
public static function getGalleryCounts(){
$galleryCounts = array();
$galleryCounts['all'] = count(Gallery::all());
$galleryCounts['allActive'] = count(Gallery::where('status','=','on')->get());
$galleryCounts['allInActive'] = count(Gallery::where('status','=','off')->get());
$galleryCounts['personal'] = count(Gallery::where('type','=','1')->get());
$galleryCounts['personalActive'] = count(Gallery::where('type','=','1')->where('status','=','on')->get());
$galleryCounts['personalInActive'] = count(Gallery::where('type','=','1')->where('status','=','off')->get());
$galleryCounts['corporate'] = count(Gallery::where('type','=','2')->get());
$galleryCounts['corporateActive'] = count(Gallery::where('type','=','2')->where('status','=','on')->get());
$galleryCounts['corporateInActive'] = count(Gallery::where('type','=','2')->where('status','=','off')->get());
return $galleryCounts;
}
Admincontroller.php
public function editGalleryForm($type,$id){
$data['id'] = $id;
$data['type'] = $type;
$data['galleryCounts'] = Gallery::getGalleryCounts();
$data['image'] = Gallery::getGalleryById($id);
$data['personalTags'] = GalleryTag::getPersonalActive();
$data['corporateTags'] = GalleryTag::getCorporateActive();
return View::make('admin.editGalleryForm', $data);
}
Formcontroller.php
public function editGallery(){
$type = Input::get('type');
$editId = Input::get('Id');
$filename=Input::get('image');
$rules = array(
'order'=>'Numeric');
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
$data['type'] = $type;
$data['Id'] = $editId;
return Redirect::route('editGalleryForm',$data)->withInput()->withErrors($validation);
}
if ($validation->passes()) {
$fileName='';
if (Input::hasFile('image')) {
$name = Input::file('image')->getClientOriginalName();
$destinationPath = 'assets/img/gallery/';
$data['Id'] = $Id;
$fileName = $name;
Input::file('image')->move($destinationPath, $fileName);
//Gallery::convertImage($destinationPath,$fileName);
}
$editGallery = Gallery::editGallery(Input::all());
if ($editGallery) {
$data['success'] = 'Gallery Image Updated!';
$data['type'] = $type;
return Redirect::route('newGallery',$data);
}
else
{
$data['failure'] = 'Operation failed!';
$data['type'] = $type;
return Redirect::route('newGallery',$data);
}
}
}
this is the form
#extends('admin.layouts.master')
#section('pageHeader')
<h2>Edit Gallery Image</h2>
<ol class="breadcrumb">
<li>{{HTML::linkRoute('adminHome','Dashboard')}}</li>
<li>{{HTML::linkRoute('newGallery','Gallery',array('type'=>$type))}}</li>
<li class="active">Edit Gallery Image</li>
</ol>
#stop
#section('content')
<div class="cl-mcont">
<div class="status_bar">
<div class="butpro butstyle {{($type=='1')? 'status_active':''}}"><a href="{{URL::route('newGallery',array('type'=>'1'))}}">
<div class="sub"><h2>PERSONAL</h2><span id="total_clientes">{{$galleryCounts['personal']}} Image{{($galleryCounts['personal'] > 1)? 's':''}}</span></div>
<div class="stat">{{$galleryCounts['personalActive']}} <i style="color:#00FF00" class="fa fa-check"></i> {{$galleryCounts['personalInActive']}} <i style="color:#FF0000" class="fa fa-times"></i></div>
</a></div>
<div class="butpro butstyle {{($type=='2')? 'status_active':''}}"><a href="{{URL::route('newGallery',array('type'=>'2'))}}">
<div class="sub"><h2>CORPORATE</h2><span id="total_clientes">{{$galleryCounts['corporate']}} Image{{($galleryCounts['corporate'] > 1)? 's':''}}</span></div>
<div class="stat">{{$galleryCounts['corporateActive']}} <i style="color:#00FF00" class="fa fa-check"></i> {{$galleryCounts['corporateInActive']}} <i style="color:#FF0000" class="fa fa-times"></i></div>
</a></div>
</div>
<div class="row">
<div class="col-md-12">
{{Form::open(array('action'=>'editGallery','method'=>'POST','files'=>true,'class'=>'form-horizontal'))}}
<div class="form-group">
{{Form::label('forType', 'Type', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::select('type', array('1'=>'personal','2'=>'corporate'), ($image->type=='2')? '2':'1', array('class'=>'form-control','onChange'=>'tagChange(this)'))}}
<div class="color-danger">{{$errors->first('type')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forTag', 'Tag', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<select class="form-control" id="tags" name="tag">
#if($type == 2)
#foreach($corporateTags as $tag)
<option {{($image->tag == $tag->id)? 'selected':''}} value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
#else
#foreach($personalTags as $tag)
<option {{($image->tag == $tag->id)? 'selected':''}} value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
#endif
</select>
<div class="color-danger">{{$errors->first('tag')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forTitle', 'Title', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::text('title', $image->title, array('class'=>'form-control','placeholder'=>'Image Title'))}}
<div class="color-danger">{{$errors->first('title')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forImage', 'Gallery Image', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::file('forimage', array('class'=>'form-control','placeholder'=>'image'))}} (600 X 400)px
<div class="color-danger">{{$errors->first('image')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('', '', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="col-md-2 padding photo">
<img src="{{asset('assets/img/gallery/'.$image->image)}}" width="200px" height="120px">
</div>
</div>
</div>
<div class="form-group">
{{Form::label('forOrder', 'Order', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::text('order', $image->position, array('class'=>'form-control','placeholder'=>'Image Order'))}}
<div class="color-danger">{{$errors->first('order')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forStatus', 'Publish Status', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="switch" data-on="success">
<input type="checkbox" name="status"{{($image->status=='on')? 'checked':''}}>
</div>
</div>
</div>
<div class="form-group">
{{Form::label('forShow', 'Show on Homepage', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="switch" data-on="success">
<input type="checkbox" name="home"{{($image->home=='on')? 'checked':''}}>
</div>
</div>
</div>
{{Form::text('editId', $image->id, array('style'=>'display:none'))}}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
{{Form::submit('Update Gallery', array('class'=>'btn btn-primary'))}}
{{HTML::linkRoute('newGallery','Cancel',array('type'=>$type),array('class'=>'btn btn-default'))}}
</div>
</div>
{{Form::token().Form::close()}}
</div>
</div>
</div>
#stop
#section('customScripts')
<script type="text/javascript">
function tagChange(element){
console.log(element.value);
$('#tags').empty();
$.ajax({
url:'{{URL::route("getTagsAjax")}}',
type:'POST',
data:{'type':element.value},
dataType:'JSON',
success:function(data){
console.log(data);
for (var i = 0; i <= data.length; i++) {
$('#tags').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
};
}
});
}
</script>
#stop

How to display the array element to view

I have a problem regarding the return view('doctor_index', compact('result') on my contoller
here is my controller
public function index()
{
$data = Auth::user()->patient;
$data = explode(',', $data);
foreach ($data as $key => $datas) {
$result = DB::table('patients')->where('id', $datas)->get();
foreach ($result as $key => $res) {
$output = ' <h4><b>'. $res->patient_name .'</b></h4>
</p>Birthday: <strong>'. $res->post_date .'</strong> Age: <strong>'. $res->patients_age .'</strong></p>
<p>Address: <strong>'. $res->patient_address .'</strong></p><br><br>';
}
echo $output;
// return view('doctor_index', compact('output'));
}
}
at first i used echo $output; this is what it displayed
Output of echo $output:
Now if i use the return view on the controller it displays
Output of the return view:
as you can see when i use the return view it only display the first element
My question is how can i display all of the elements to my view using the return view
my view code:
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-body">
<div class="col-md-12">
<h2><b>{{ Auth::user()->name }} </b></h2>
<p>Email: <strong> {{ Auth::user()->email }} </strong></p>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<div class="col-md-12">
<h3>Patients</h3>
</div>
<div class="col-md-12">
<div class="container">
<?php echo $output ?>
</div>
</div>
</div>
</div>
</div>
With functions and methods once it reaches the return statement it won't continue through the other loops. Instead you should pass the array to the view and loop over the array within your view. So your controller would look something like this:
public function index()
{
$data = Auth::user()->patient;
$data = explode(',', $data);
$responseData = [];
foreach ($data as $key => $datas) {
$result = DB::table('patients')->where('id', $datas)->get();
foreach ($result as $key => $res) {
$responseData[] = ' <h4><b>'. $res->patient_name .'</b></h4>
</p>Birthday: <strong>'. $res->post_date .'</strong> Age: <strong>'. $res->patients_age .'</strong></p>
<p>Address: <strong>'. $res->patient_address .'</strong></p><br><br>';
}
}
return view('doctor_index', compact('responseData'))
}
And then your blade template would look something like this.
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-body">
<div class="col-md-12">
<h2><b>{{ Auth::user()->name }} </b></h2>
<p>Email: <strong> {{ Auth::user()->email }} </strong></p>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<div class="col-md-12">
<h3>Patients</h3>
</div>
<div class="col-md-12">
<div class="container">
#foreach($responseData as $output)
{!! $output !!}
#endforeach
</div>
</div>
</div>
</div>
</div>

Codeigniter : How to detect the first row of a query result

My viewis like below.
<div class="carousel-inner">
<?php
foreach($news_data as $nws){
?>
<div class="item **If this is the first row, then echo active**">
<div class="col-md-12 news-item" style="padding-left: 0;">
<p><?php echo $nws->news_desc; ?></p>
</div>
</div>
<?php } ?>
</div>
Model:
function get_news_update()
{
$this->db->select('news_desc');
$this->db->from('news');
$this->db->where('stat', '1');
$this->db->order_by('id', 'desc');
$query = $this->db->get();
return $query->result();
}
Please see the <div class="item. If it is the first row of query result, then it will be item active.
How to do that ?
Modify your view like this:
<div class="carousel-inner">
<?php
foreach($news_data as $key => $nws){
?>
<div class="item <?php echo $key == 0 ? "active":""; ?>">
<div class="col-md-12 news-item" style="padding-left: 0;">
<p><?php echo $nws->news_desc; ?></p>
</div>
</div>
<?php } ?>
</div>
Here is your updated code
<div class="carousel-inner">
<?php
$i = 0;
foreach($news_data as $nws){
// it should be $i. not $i%2 right ?
if($i == 0)
{
$class="item active";
}
else
{
$class = "item";
}
?>
<div class="<?php echo $class; ?>">
<div class="col-md-12 news-item" style="padding-left: 0;">
<p><?php echo $nws->news_desc; ?></p>
</div>
</div>
<?php $i++; } ?>
</div>
As per my knowledge,You are looking for below code.Please let me know if its not working.
function get_news_update()
{
$this->db->select('news_desc');
$this->db->from('news');
$this->db->where('stat', '1');
$this->db->order_by('id', 'desc');
$query = $this->db->get();
return $query->first_row();
}
You can use row() function, which return always the first result.
Model.php
function get_news_update(){
$this->db->select('news_desc');
$this->db->from('news');
$this->db->where('stat', '1');
$this->db->order_by('id', 'desc');
$query = $this->db->get();
//check if exist
if (isset($query->row())){
return $query->row();
}
}
For more informations you will find here
View.php
<div class="carousel-inner">
<div class="item **If this is the first row, then echo active**">
<div class="col-md-12 news-item" style="padding-left: 0;">
<p><?php echo $nws->news_desc; ?></p>
</div>
</div>
</div>

codeigniter invalid argument supplied for foreach() on join clause

i try all of away that i know and suggestion on internet.
but all time return false.
please help me...
thanks
my error message is:
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/index.php
Line Number: 10
model.php
public function getBanner()
{
$this->db->select('album.id, album.cat_id , album.poster, album.slug, album.modify, category.id, category.name, category.slug');
$this->db->from('album,category');
$this->db->where('album.cat_id', 'category.id');
$query = $this->db->get();
if($query->num_rows() != 0)
{
$result = $query->result_array();
return $result;
}
else
{
return false;
}
}
controllers.php
$data['banner'] = $this->Fornt_model->getBanner();
showbanner.php
<section class="banner">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<?php $item = 1; foreach($banner as $latest_poster): $item_class = ($item == 1) ? 'item active' : 'item'; ?>
<div class="<?php echo $item_class; ?>">
<img src="<?php echo base_url('images/poster/'.$latest_poster['poster']); ?>" class="img-responsive img-thumbnail">
<div class="carousel-caption caption">
<a href="<?php echo site_url('category/bollywood/'.$latest_poster['slug']); ?>" class="box">
<b class="h3"><?php echo $latest_poster['name']; ?></b>
<small class="p">Exclusive AT*<?php echo substr($latest_poster['modify'], 0, 10); ?></small>
</a>
</div>
</div>
<?php $item++; endforeach; ?>
</div>
</div>
</div>
</div>
<div class="clearfix" style="padding: 10px 0;"></div>
<div class="row hidden-xs">
<?php $itemto = 0; foreach($banner as $latest_poster): $item_class_active = ($itemto == 0) ? 'active' : ''; ?>
<div class="col-sm-2 pointer" data-target="#myCarousel" data-slide-to="<?php echo $itemto; ?>"><img src="<?php echo base_url('images/poster/'.$latest_poster['poster']); ?>" class="img-responsive img-thumbnail" /></div>
<?php $itemto++; endforeach; ?>
</div>
</div>
I think something wrong with your query.. try
if($query->num_rows() != 0)
{
$result = $query->result_array();
print_r($result);
}
make sure your array data is available..
If there is no rows, front_model->getBanner() will return the result as false. Due to this you are getting an error. Use following code
public function getBanner()
{
$this->db->select('album.id, album.cat_id , album.poster, album.slug, album.modify, category.id, category.name, category.slug');
$this->db->from('album,category');
$this->db->where('album.cat_id', 'category.id');
$query = $this->db->get();
return $query->result_array();
}

Form Validation Showing 2 Callback Messages

I am trying to set my own callback message for codeigniter. But when I try to make my own it will show both messages codeigniter one and my custom one. Here is a link to my errors are showing up the top error is one that I would like to use http://postimg.org/image/v9ilejmnt/
How am I able to make it only show my custom error message?
I also use hmvc so I have had to add run($this) in the form validation to make callback work.
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('user');
$this->load->library('form_validation');
$this->lang->load('common/login', 'english');
if($this->session->userdata('user_id')) {
redirect('dashboard');
} else {
return false;
redirect('login');
}
}
public function index() {
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[12]|xss_clean|callback_validate');
$this->form_validation->set_rules('password', 'Password', 'required|xss_clean');
if($this->form_validation->run($this) == false) {
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('login');
$this->load->view('common/login', $data);
} else {
redirect('dashboard');
}
}
function validate() {
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->user->login($username, $password)) {
return true;
} else {
$this->error['warning'] = $this->lang->line('error_login');
return !$this->error;
}
}
}
View
<?php echo modules::run('common/header/index');?>
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-3 col-md-4 col-md-offset-4 col-sm-offset-4 col-sm-4">
<div class="panel panel-default">
<div class="panel-heading"><h2 class="panel-title">Administration Login</h2></div>
<div class="panel-body">
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
<form action="<?php echo $action;?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="input-group"><span class="input-group-addon"><i class="fa fa-user"></i> </span>
<input type="text" name="username" value="" placeholder="Username" class="form-control" size="50" />
</div>
<?php echo form_error('username', '<div class="text-danger">', '</div>'); ?>
</div>
<div class="form-group">
<div class="input-group"><span class="input-group-addon"><i class="fa fa-lock"></i></span>
<input type="password" name="password" value="" placeholder="Password" class="form-control"/>
</div>
<?php echo form_error('password', '<div class="text-danger">', '</div>'); ?>
</div>
<div class="form-group">
<div class="text-right">
<button type="submit" class="btn btn-primary"><i class="fa fa-key"></i> Login</button>
</div>
</div>
</form>
</div><!--/. Panel Body -->
</div><!--/. Panel Panel Default -->
</div>
</div>
</div>
<?php echo modules::run('common/footer/index');?>
you forgot to set error message for your your callback.
$this->form_validation->set_message('validate', 'invalid username or password');
return FALSE;
or you can do
$this->form_validation->set_message('validate', $this->lang->line('error_login'));
return FALSE;
in your view file you are showing errors for each fields (CI form validation messages) as well as your own <?php echo $error_warning; ?>
you should use following code
function validate() {
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->user->login($username, $password)) {
return true;
} else {
$this->form_validation->set_message('validate', $this->lang->line('error_login'));
return FALSE;
}
and remove this block from view
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
}
and remove this too
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
I worked it out today. When want to use both validation methods custom and form validation can not use callbacks.
public function index() {
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|xss_clean');
if($this->form_validation->run($this) == false) {
$data['title'] = $this->lang->line('heading_title');
$data['text_heading'] = $this->lang->line('text_heading');
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('login');
$this->load->view('common/login', $data);
} else {
if($this->validate()) {
redirect('dashboard');
} else {
$data['title'] = $this->lang->line('heading_title');
$data['text_heading'] = $this->lang->line('text_heading');
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('login');
$this->load->view('common/login', $data);
}
}
}

Resources