I am using version CodeIgniter 2.1.4. I have problem on displaying form validation error. form validation is returning false but validation_errors() is not displaying any errors. I have tried to echo in controller and in view but no result. I am giving request through ajax.no php errors are thrown.
Controller:
<?php
class Dashboard extends Admin_Controller {
public function ajax_new_dist_center($id=NULL)
{
$this->load->model('dist_centre_m');
$this->load->helper(array('form', 'url'));
$this->load->library('Form_validation');
$validation = $this->dist_centre_m->rules;
$this->form_validation->set_error_delimiters('<li>', '</li>');
$this->form_validation->set_rules($validation);
if ($this->form_validation->run() == TRUE)
{
if($this->dist_centre_m->create($id))
echo 'New centre created';
else
{
$this->output->set_status_header('404');
echo 'Given center not found';
}
}
else
{
$this->output->set_status_header('400');
echo 'validation Failed';
$this->load->view('alert_error');
}
}
}
View:
<?php echo validation_errors();?>
<p>Testing Error</p>
Model:
class dist_centre_m extends MY_Model {
protected $_table_name = 'distribution_centre';
protected $_primary_key = 'dis_id';
protected $_order_by = 'dis_id';
public $rules = array(
'name' => array(
'field'=>'name',
'label'=>'Center name',
'rules'=>'trim|required|xss_cleaned|min_length[3]|max_length[45]'
),
'street' => array(
'field'=>'street',
'label'=>'Street',
'rules'=>'trim|required|xss_cleaned|min_length[3]|max_length[45]'
),
'town' => array(
'field'=>'town',
'label'=>'Town',
'rules'=>'trim|required|min_length[3]|max_length[45]|required|xss_cleaned'
),
'postcode' => array(
'field'=>'postcode',
'label'=>'Postcode',
'rules'=>'trim|required|max_length[10]|required|xss_cleaned'
),
'tel' => array(
'field'=>'tel',
'label'=>'Telephone number',
'rules'=>'trim|valid|exact_length[11]|required|xss_cleaned'
),
);
public function __construct() {
parent::__construct();
$this->load->helper('security');
}
public function create($id=NULL){
$data = array(
'name' =>$this->input->post('name',true),
'street' =>$this->input->post('street',true),
'town' =>$this->input->post('town',true),
'postcode' =>$this->input->post('postcode',true),
'tel' =>$this->input->post('tel',true),
);
return $this->save($data,$id);
}
}
Output:
validation Failed
Testing Error
None of the related question is working please do not mark duplicate.
Update:
My Ajax request page:
<form id="new-center-form" method="post">
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Name"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for='street'>Street</label>
<input type="text" name="street" placeholder="Street"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="town">Town</label>
<input type="text" name="town" placeholder="Town"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="postcode">Postcode</label>
<input type="text" name="postcode" placeholder="Postcode"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="tel">Phone</label>
<input type="text" name="tel" placeholder="Telephone"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<button id="centre-submit" class="btn btn-primary pull-left">Save</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
var url_new_center = '<?php echo page_url('new-center') ?>';
$('#centre-submit').click(function(e){
e.preventDefault();
$.ajax({
url:url_new_center,
type:'post',
data: $('new-center-form').serialize()
}).done(function(response){
$('#infos').html(response);
$('#infos').slideDown();
$('.new-centre').slideUp();
}).fail(function(response){
$('#errors').html(response);
$('#errors').slideDown();
});
})
});
</script>
Finally after a long sleep I figured out.$this->form_validation->run() returns false when no $_POST data found and it will not set any errors to print. In my ajax request due to some errors it could not send any data. Thanks for curl I was able to test it.
update
data: $('new-center-form').serialize() // this was the error.
I made a typo here. this should be like this data: $('#new-center-form').serialize()
let me make your answer more clear.
It is not because no $_POST data found like you said,
it is actually because that there are no RELATED $_POST data that you have set rules for them in your model.
There may have been any other $_POST data exclude for those that you have set rules for:
'name' , 'street' , 'town' , 'postcode' , ' tel'
then the CI validator could not find any of the elements that rules have been set so the form_validation->run() will definitely return false
And certainly the validation_errors() will not show anything because there are nothing to apply the specified rules on.
Related
This is a question I have seen asked before but I have been unable to find an answer for the newer version of Codeigniter.
Controller
<?php
namespace App\Controllers;
class SendEmail extends BaseController
{
public function index($validation = NULL){
// Load form helper
helper('form');
// Instantiate session
$session = \Config\Services::session();
// Set css, javascript, and flashdata
$data = [
'css' => array('contact.css'),
'js' => array('contact.js'),
'validation' => $validation,
'success' => $session->get('success')
];
// Show views
echo view('templates/header', $data);
echo view('contact', $data);
echo view('templates/footer', $data);
}
public function sendEmail(){
// Instantiate request
$request = $this->request;
// Captcha API
$captchaUser = $request->getPost('g-recaptcha-response');
// Captcha Key loaded from a file left out of the repo
$captchaConfig = config('Config\\Credentials');
$captchaKey = $captchaConfig->captchaKey;
$captchaOptions = [
'secret' => $captchaKey,
'response' => $captchaUser
];
$client = \Config\Services::curlrequest();
$captchaResponse = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', ['form_params' => $captchaOptions]);
$captchaObj = json_decode($captchaResponse->getBody());
// Load validation library
$validation = \Config\Services::validation();
// Set validation rules
$validation->setRules([
'name' => 'required|alpha_dash|alpha_space',
'email' => 'required|valid_email',
'subject' => 'required|alpha_numeric_punct',
'message' => 'required|alpha_numeric_punct'
]);
// Validate inputs
if (!$this->validate($validation->getRules())){
// Run index function to show the contact page again
$this->index($this->validator);
}
// Validate captcha
elseif(!$validation->check($captchaObj->success, 'required')){
$validation->setError('captcha','Did not pass captcha. Please try again.');
$this->index($validation->getErrors());
}
else{
// Set variables to input
$name = $request->getPost('name');
$email = $request->getPost('email');
$subject = $request->getPost('subject');
$message = $request->getPost('message');
// Load email class
$emailC = \Config\Services::email();
// Set email settings
$emailC->setFrom('bensirpent07#benkuhman.com', $name);
$emailC->setReplyTo($email);
$emailC->setTo('benkuhman#gmail.com');
$emailC->setSubject($subject);
$emailC->setMessage($message);
// Testing section
echo '<br>'.$name.'<br>'.$email.'<br>'.$subject.'<br>'.$message;
/* Temporarily disabled for testing purposes
// Send email
if($emailC->send(false)){
// Redirect
return redirect()->to(base_url().'/contact')->with('success', true);
}else{
// Display error
throw new \CodeIgniter\Database\Exceptions\DatabaseException();
};
*/
}
}
}
Contact View
<div class="container">
<div class="row">
<div class="col">
<div class="alert alert-success align-center" id="message-alert" <?php if($success){echo 'style="display:block"';} ?>>Message successfully sent!</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<?php echo form_open('send_email', ['id'=>'contactForm'])?>
<div class="form-group">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="name" placeholder="Name" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('name')){echo $validation->getError('name');}?></p>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input name="email" type="email" class="form-control" id="email" aria-describedby="email" placeholder="E-mail" required>
<small id="emailHelp" class="form-text">I'll never share your email with anyone else.</small>
<?php //echo $validation->email;?>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('email')){echo $validation->getError('email');}?></p>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="Subject" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('subject')){echo $validation->getError('subject');}?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" rows="5" class="form-control" id="message" placeholder="Type your message here." required></textarea>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('message')){echo $validation->getError('message');}?></p>
</div>
<button id="submitButton" type="submit" class="btn btn-primary g-recaptcha" data-sitekey="6Ldf07AZAAAAAAflQCaJcWgGFCWevCswpIrm0mJN" data-callback='onSubmit' data-action='submit'>Submit</button>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('captcha')){echo $validation->getError('captcha');}?></p>
<?php echo form_close()?>
</div>
</div>
</div>
<script>
function onSubmit(token) {
document.getElementById("contactForm").submit();
}
</script>
<script src="https://www.google.com/recaptcha/api.js"></script>
From my understanding of the way validation used to work in CodeIgniter, is that when you loaded your view after a form validation it would update the values with what was previously entered. This does not seem to be the case for CodeIgniter 4. I've also tried directly loading the views rather than calling the index function on validation fail. Still would not fill in the form values.
Now I could just pass these values to the index function via $data array. Which is the fix I'm going to use for now. This is more so a sanity check to see if there is something basic I'm missing or if I'm incorrectly using the validation format for CodeIgniter 4.
in CI4 you can use old() function to preserve the input value upon form validation:
View file:
<input type="tel" name="phone" value="<?= old('phone'); ?>">
In Controller you must use withInput() in the redirect() code:
$validation = \Config\Services::validation();
$request = \Config\Services::request();
// your input validation rules
$validation->setRules(...)
if($request->getMethod() == "post" && ! $validation->withRequest($request)->run()) {
return redirect()->back()->withInput()->with('error', $this->validation->getErrors());
} else {
// form validation success
}
I am making a news editing feature using CodeIgniter 3, there is also an image edit here
But has errors like the following,
An uncaught Exception was encountered
Type: ArgumentCountError
Message: Too few arguments to function Operator::edit_berita(), 0 passed in D:\xampp\htdocs\ui-desa\system\core\CodeIgniter.php on line 532 and exactly 1 expected
Filename: D:\xampp\htdocs\ui-desa\application\controllers\Operator.php
Line Number: 164
Backtrace:
File: D:\xampp\htdocs\ui-desa\index.php
Line: 315
Function: require_once
Controller Operator.php
public function edit_berita($id_berita)
{
$data['title'] = 'Edit Berita';
$data['user'] = $this->db->get_where(
'user',
['id' => $this->session->userdata('id')],
['email' => $this->session->userdata('email')]
)->row_array();
$data['berita'] = $this->model_berita->getAllBeritaById($id_berita);
// $data['berita'] = $this->db->get('berita')->result_array();
// $data['berita'] = $this->model_berita->getNama();
$this->form_validation->set_rules('judul_berita', 'Judul Berita', 'required');
$this->form_validation->set_rules('isi_berita', 'Isi Berita', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('operator/editberita', $data);
$this->load->view('templates/footer');
} else {
$judul_berita = $this->input->post('judul_berita');
$slug_berita = url_title($this->input->post('judul_berita'), 'dash', 'TRUE');
$isi_berita = $this->input->post('isi_berita');
$tgl_berita = date('Y-m-d H:i:s');
$id = $this->session->userdata('id');
// Cek Jika Ada Gambar Yang DiUpload
$upload_image = $_FILES['gambar_berita'];
if ($upload_image) {
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['upload_path'] = './gambar_berita/';
$this->load->library('upload', $config);
if ($this->upload->do_upload('gambar_berita')) {
$old_image = $data['berita']['gambar_berita'];
if ($old_image != 'default.jpg') {
unlink(FCPATH . 'gambar_berita/' . $old_image);
}
$new_image = $this->upload->data('file_name');
$this->db->set('gambar_berita', $new_image);
} else {
echo $this->upload->display_errors();
}
}
$this->db->set('id_berita', $id_berita);
$data = array(
'judul_berita' => $judul_berita,
'isi_berita' => $isi_berita
);
$this->db->where($data);
$this->db->update('berita');
$this->session->set_flashdata('message', '<div class="alert alert-success" role ="alert"> Berita Berhasil di Reposting </div>');
redirect('operator/berita');
}
}
Model model_berita.php
public function getAllBeritaById($id_berita)
{
return $this->db->get_where('berita', ['id_berita' => $id_berita])->row_array();
}
View edit_berita.php
<!-- CK Editor 4 -->
<script src="<?= base_url('ckeditor/'); ?>ckeditor.js"></script>
<script src="<?= base_url('ckeditor/'); ?>samples/js/sample.js"></script>
<link href="<?= base_url('ckeditor/'); ?>samples/css/samples.css" rel="stylesheet">
<link href="<?= base_url('ckeditor/'); ?>samples/toolbarconfigurator/lib/codemirror/neo.css" rel="stylesheet">
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">
<?= $title; ?></h1>
<div class="row">
<div class="col-lg">
<?php if (validation_errors()) : ?>
<div class="alert alert-danger" role="alert">
<?= validation_errors(); ?>
</div>
<?php endif; ?>
<?= $this->session->flashdata('message'); ?>
<?= form_open_multipart('operator/edit_berita') ?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $berita['id_berita']; ?>">
<div class="modal-body">
<div class="form-group">
<small>Masukkan Judul Berita</small>
<input type="text" value="<?= $berita['judul_berita']; ?>" class="form-control" id="judul_berita" name="judul_berita" placeholder="Judul Berita..." required>
</div>
<div class="form-group">
<small>Masukkan Isi Berita</small>
<textarea class="form-control" name="isi_berita" id="editor" required><?= $berita['isi_berita']; ?></textarea>
</div>
<div class="form-group">
<label for="gambar_berita">Ganti Gambar Berita</label>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-3">
<img src="<?= base_url('gambar_berita/') . $berita['gambar_berita']; ?>" class="img-thumbnail" alt="Gambar Berita">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="gambar_berita" name="gambar_berita">
<label class="custom-file-label" for="gambar_berita">Choose File</label>
</div>
</div>
</div>
</div>
<br>
<button type="reset" class="btn btn-danger" data-dismiss="modal">Reset</button>
<button type="submit" class="btn btn-primary">Add</button>
</div>
</form>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<script>
initSample();
</script>
I've tried a number of ways, but it's still an error too. Please help so that my news update feature can work. Thanks.
Well your error clearly states that your method.
public function edit_berita($id_berita)
is expecting a parameter, which you have named $id_berita.
I cannot tell why you decided to have a parameter in this method, so I can only make some suggestions to help you solve your issue.
From what I can gather from your supplied code you could try the following options...
Option 1:
From what I can tell from your form, you are posting this as a hidden input, so you should be retrieving it from the Post Data.
<input type="hidden" name="id" value="<?= $berita['id_berita']; ?>">
So your method should become...
public function edit_berita()
{
$id_berita = $this->input->post('id'); // This needs to be validated
// The rest of your code below here...
}
But I would be validating that value to see if it exists before processing anything else.
Personally, I would be naming it as id_berita in your form to keep things matched up to avoid mistakes.
Option 2:
Another option would be to modify your form_open_mulitpart from
<?= form_open_multipart('operator/edit_berita') ?>
To include the id to pass in as a parameter
<?= form_open_multipart('operator/edit_berita/'.$berita['id_berita']) ?>
You will have to check that by inspecting your HTML Source using your Browsers "View Source" and inspect the HTML to see that it has ended up in the right place.
That will let you use your existing method
public function edit_berita($id_berita)
But again, you would need to validate that the passed in $id_berita is correct.
Which ever way you go, is your choice. You just need to read through your code and understand it a bit better.
I hope that gives you some guidance.
I'm trying to edit some data from database for a certain id which is selected from the edit button in another form.
It would help me if you can explain what is happening here, I'm new to laravel, I have tried to understand the documentation but I didn't find any explanation for this
<form action="{{route('listaasdjoburi.updaasdte', $isd)}}" method="post" enctasdype="multasdipart/foasdrm-dasdata">
#csrf
<div class="box-body">
<div class="form-group">
<label for="exampleInputEmail1">Nume Job</label>
<input type="tasdext" class="form-casdontrol" id="tiasdtlu" name="titlu" value="{{$jobuasdri->tiasdtlu}}"/>
</div>
<div class="form-group">
<label for="exampasdleInputPassword1">Desasdcriere:</label>
<input type="teasdxt" class="foasdrm-control" id="deasdscriere" name="descriere" value="{{$joburi->descriere}}"/>
</div>
<div class="form-gasdroup">
<label for="exampleIasdnputPassword1">Salaasdriu Estiasdmativ:</labasdel>
<input type="text" class="form-control" id="salarasdiu_asdestimativ" name="sasdalariu_estimasdativ" value="{{$joasdburi->salasdariu_estimasdativ}}"/>
</div>
<div claasdss="form-gasdroup">
<label for="exampasdleInpuasdtPassword1">Orasds:</label>
<input type="teasdxt" class="forasdm-control" id="orasdas" name="oasdras" value="{{$jobasduri->oraasds}}"/>
</div>
<div class="form-group">
<label for="exampleInpasdutPassword1">Actasdiv(1=actasdiv,0=inactasdiv)</label>
<input type="tasdext" class="form-control" id="aasdctiv" name="aasdtiv" value="{{$jobasduri->actiasdv}}">
</div>
this is the controller
public function index()
{
$jobuasdri = Joadsburi::all()->toasdArray();
return view('listajasdoburi', compasdact('jobasduri'));
}
public function easddit($id)
{
$jobasduri = Jobasduri::fiasdnd($id);
return view('editaasdrejob', compasdact('joasdburi', 'iasdd'));
}
public function update(Requasdest $requasdest, $iasdd)
{
$this->validasdator($requasdest->all());
$update = Jobuasdri::fiasdnd($id)->upasddate([
'titasdlu' => $request->tasditlu,
'descasdriere' => $request->dasdescriere,
'salaasdriu_estasdimativ' => $request->salarasdu_estimasdativ,
'oraasds' => $reqasduest->asdoras,
'activ' => $reqasduest->aasdctiv,
// 'skasdill' => $requasdest->ciasdty,
]);
if ($updaasdte) {
returasdn redasdirect()->route('lisasdtajoburi.updasdate')->witasdhSuccess('S-a modifiasdcat cvu suasdccess!');
} else {
return rediasdrect()->back()->wiasdthDanger('Nu s-a moasddificat! A apaasdrut o eroasdare.');
}
}
protected function validasdator(array $daasdta)
{
return Validaasdtor::masdake($dasdata, [
'tiasdtlu' => ['requasdired', 'striasdng', 'masdin:3', 'masdax:255'],
'descasdiere' => ['requasdired', 'striasdng', 'max:11'],
'salarasdiu_estimativ' => ['requasdired', ''],
'orasdas' => ['stasdring', 'max:512asd'],
'actasdiv' => ['requasdired', 'strasding', 'max:asd512'],
// 'skiasdll' => ['sasdtring', 'maasdx:45'],
]);
}
}
and this is the route
Route::get('/listajasdasdoburi', 'asdAuth\ListasdaJoburiController#index')->name('listajoasdburi');
Route::get('/editasdarejob/{idasd}/', 'Auasdth\ListaJoburiController#edit')->name('editarejasdob');
Route::post('/listasdajoburiupdate/{id}', 'Auth\LisasdtaJoburiController#update')->nasdame('listajoburasdi.updaasdte');
The problem is that your route look like this:
Route::post('/listajoburiupdate/{id}', 'Auth\ListaJoburiController#update')->name('listajoburi.update');
And you try to make redirection like this in your controller:
return redirect()->route('listajoburi.update')->withSuccess('S-a modificat cu success!');
so you don't pass id here. It should be probably:
return redirect()->route('editarejob', $id)->withSuccess('S-a modificat cu success!');
because:
you cannot make redirection to route that uses POST - you can only make redirection to route that uses GET (in this case to edit form)
you need to pass id because both 2nd and 3rd route need {id} parameter
I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.
I have been having a problem... a frustrating problem at that. I cannot seem to edit a specific row in Codeigniter. I have found previous questions on the same here, and even tried the solutions but to no avail. I am press for time on this project I am undertaking. Before you regard this question as a duplicate please have a look see. Any help will be greatly appreciated... Thank you in advance My code snippets are below:
Codeigniter/Controller
<?php..
//Selects all from admin table
function get_admin(){
$data['query'] = $this->Superuser_Model->selectadmin();
}
//brings in the view
// function editAdmin(){
// $data['content'] = 'admin/edit_admin';
// $this->load->view('include/template_back', $data);
// }
//click a specific row in the view (tabulated data)
function edit($id){
$data['array']= $this->Superuser_Model->editadmin($id);
// $data['content'] = 'admin/edit_admin';
$this->load->view('include/header_back');
$this->load->view('admin/edit_admin', $data);
$this->load->view('include/footer_back');
}
//Should update the from
function update_superuser(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run()==FALSE)
{
$data['content'] = 'admin/add_admin';
$this->load->view('include/template_back', $data);
}
else
{
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$date_added = $this->input->post('date_added');
$this->Superuser_Model->update_superuser($username,$password,$date_added);
redirect('login/index', 'refresh');
}
}
..?>
Codeigniter/Model
<?php...
function selectadmin(){
// $id = $this->uri->segment(3);
$query = $this->db->get('admin');
return $query->result_array();
}
function editadmin($id){
$id = $this->uri->segment(3);
$query = $this->db->get('admin');
$this->db->where('adminID', $id);
return $query->result_array();
}
function update_superuser($data, $id){
$this->uri->segment(3);
$id = $this->input->post('adminID');
$data = array(
'username'=> $this->input->post('username'),
'password'=> $this->input->post('password'),
'date_added'=> $this->input->post('date_added')
);
$this->db->where('adminID', $id);
$this->db->update('admin', $data);
}
...?>
Codeigniter/View
...
<?php echo form_open('superuser/update_superuser', array('class' => 'form-horizontal', 'enctype' => 'multipart/form-data')); ?>
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-btns">
×
−
</div>
<h4 class="panel-title">Admin Details</h4>
<p>Please, Insert your details here below... (for Superuser use only)</p>
</div>
<div class="panel-body panel-body-nopadding">
<!--username-->
<div class="form-group">
<!-- <input type="hidden" name="adminID" class="form-control" value="<?php echo $array->adminID;?>"/> -->
<label class="col-sm-4 control-label">Username</label>
<div class="col-sm-8">
<input type="text" name="username" class="form-control" value="<?php echo $array['username'];?>"/>
</div>
// <?php // form_error('username');?>
</div>
<!--password-->
<div class="form-group">
<label class="col-sm-4 control-label">Password</label>
<div class="col-sm-8">
<input type="password" name="password" class="form-control" value="<?php echo $array['password'];?>"/>
</div>
<?php //echo form_error('date_added');?>
</div>
<!--Date Added-->
<div class="form-group">
<label class="col-sm-4 control-label">Date</label>
<div class="col-sm-8">
<input type="text" name="date_added" class="form-control" id="datepicker" value="<?php echo $array['date_added'];?>" /> <img src="<?php echo base_url();?>components/backend/images/calendar.gif" alt="" /><br /><br />
</div>
<?php //echo form_error('date_added');?>
</div>
</div><!-- panel-body -->
<div class="panel-footer">
<button class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div><!-- panel-footer -->
</div><!-- panel-default -->
<?php form_close();?>
...</body></html>
Errors Displayed
A PHP Error was encountered
Severity: Notice
Message: Undefined index: username
Filename: admin/edit_admin.php
Line Number: 54
A PHP Error was encountered
Severity: Notice
Message: Undefined index: password
Filename: admin/edit_admin.php
Line Number: 62
A PHP Error was encountered
Severity: Notice
Message: Undefined index: date_added
Filename: admin/edit_admin.php
Line Number: 70
Seems like not correct $array['username'], $array['password'] and $array['date_added']. Print out $array first and you'll see what's wrong.
I see a few things... Firstly, you are trying to use the $this->input->post method which is beyond the scope of the model (relevant only to the controller). This is what provides you with the php errors...
Secondly, you are passing the right parameters to the model (minus cleaning them from XSS attacks, notice), but you are accepting different ones, so in the model your function should look something like this
function update_superuser($username, $password, $data_added){
$id = $this->input->post('adminID'); // I believe you should be getting the id from the database/session honestly, much safer in these cases
$data = array(
'username'=> $username,
'password'=> $password,
'date_added'=> $data_added
);
$this->db->where('adminID', $id);
$this->db->update('admin', $data);
}
Hope this helps!
You are passing 3 parameters to your update_superuser() function here
$this->Superuser_Model->update_superuser($username,$password,$date_added);
and your function in your model only takes 2 params:
function update_superuser($data, $id){
$this->uri->segment(3);
$id = $this->input->post('adminID');
$data = array(
'username'=> $this->input->post('username'),
'password'=> $this->input->post('password'),
'date_added'=> $this->input->post('date_added')
);
$this->db->where('adminID', $id);
$this->db->update('admin', $data);
}