I'm developing a function that should enable users to update their personal information and I'm using CI form validation library. I'd want to know if what I'm doing is right.
public function updateDetails()
{
$this->load->model('users_model'); // load users model
$username = $this->input->post("username", true); // get the post from view
$this->form_validation->set_rules('username', 'Username', 'required|max_length[32]');
if($this->form_validation->run() === true)
{
// Send to model
}
}
Is this right? Or is there another method to do this?
yes so far you're right
but you should process if the validation is successful
public function updateDetails()
{
// load the library if not already loaded in config/autoload.php
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|max_length[32]');
if($this->form_validation->run() === true)
{
$this->load->model('users_model'); // load users model
$username = $this->input->post("username", true); // get the post from view
// Send to model
}
else
{
$data['error_message'] = "form not valid ...blablabla";
//go back to form
$this->load->view("form_vew",$data);
}
}
Related
I have checked all the possible things that might go wrong with my code but still it showing me this error. Please help .
Unable to access an error message corresponding to your field name Username.(check_username)
And this is my code below:
public function index()
{
if ( ! file_exists(APPPATH.'/views/login.php'))
{
/* Whoops, we don't have a page for that! */
show_404();
}
$this->load->helper('security');
$this->load->library('form_validation'); // Including Validation Library.
$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); // Displaying Errors in Div
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_check_username'); // Validation for Username Field
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); // Validation for Password field.
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
}
function check_username($username)
{
if ($username == 'test') {
$this->form_validation->set_message('check_username','already exists.');
return false;
} else {
return TRUE;
}
}
}
Do $config['global_xss_filtering'] = TRUE; in config file.
in Codeigniter-3 xss_filtering is not a part of form_validation.
You have to add the validation language in the system folder. Check the video
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&sqi=2&ved=0ahUKEwi71dGkn73MAhVBQI4KHeZJC2gQtwIIPTAF&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D56EDSocDhjk&usg=AFQjCNE_nhBpNwUOz9nkrcRYYgL50p34Kw&sig2=PSUISbtldDaWWdTyKJ6CPw&bvm=bv.121070826,d.c2E
I am pretty knew to code igniter / OOP but I am giving it a shot and a little stumped at this point.
I have 2 functions. One is the search which loads data from a model. The other is the save function.
My issue is, when running save() I am getting errors because its trying ti display the validation errors but we no longer have the data from the database that we got from the search() function.
I feel that it would be redundant to include all the details form the search back into this save function which is why I think I am doing something wrong.
public function search()
{
// Define some vars
$data['title'] = 'Submit Attrition';
$data['js_file'] = 'submit.js';
// Load our helper
$this->load->helper('form');
// Get the user and pass it to the model
$empQID = $this->input->post('empQID');
$data['userDetails'] = $this->submit_model->get_details($empQID);
$data['languages'] = $this->submit_model->get_languages();
$data['types'] = $this->submit_model->get_types();
$data['ratings'] = $this->submit_model->get_ratings();
$data['processes'] = $this->submit_model->get_processes();
// Send the data to the views
$this->load->view('templates/header', $data);
$this->load->view('submit/search', $data);
$this->load->view('templates/footer', $data);
}
/**
* Validate & save attrition submission
*
* #author Carl
* #return void
*/
public function save()
{
$data['title'] = 'Submit Attrition';
$this->load->library('form_validation');
$this->form_validation->set_rules('language', 'Supporting Language', 'required');
// Validation failed, show form w/ validation errors
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('submit/search', $data);
$this->load->view('templates/footer', $data);
}
else
{
// Success : Send data to model
$this->submit_model->save_attrition();
$this->load->view('templates/header', $data);
$this->load->view('submit/success', $data);
$this->load->view('templates/footer', $data);
}
}
I'm not sure I entirely understand your question, but I think I understand what you're trying to do. In CodeIgniter, you do something like this:
class MyController
{
// this controller action will load whether the form is submitted or not
// $user_id is set by the router
public function save($username)
{
// if the users not in the database, throw a 404 error
$user = $this->db->get_where('users', ['username' => $username]);
if(!$user) {
return show_404();
}
// if it's not a post request, then the form hasn't been submitted
// so don't bother validating it
if($router->fetch_method() === 'POST' && $form_validation->run() === TRUE)
{
$user['name'] = $this->input->post('name');
$this->db->update('users', $user);
$this->load->view('success_page');
// return so we don't render the form again
return;
}
// this will happen in all cases, __except__ when the form was submitted
// with valid data
$this->load->view('form');
}
}
I've skipped on details for brevity (like loading the relevant libraries), and because I can't remember all the CI syntax.
I just create login class that check the valid user, after that user enter in his/her home section. But now i need to change the destination of the user's home conditionally, Unable to
attach switch case in url redirection.
Note: I think varibale not properly passed in function.Plz help me
My code as Follow:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('userp','',TRUE);
}
function index($dest)
{
$this->load->view('header');
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$data['msg'] = "";
$this->load->view('login',$data);
}
$this->load->view('footer');
}
function check_database()
{
//Field validation succeeded. Validate against database
$email = $this->input->post('email');
//query the database
$password= $this->input->post('password');
$result = $this->userp->login($email,$password);
if($result!==FALSE)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' =>$row->email,
'fname' =>$row->first_name,
'lname' =>$row->last_name,
'pic'=>$row->pic
);
$this->session->set_userdata('logged_in',$sess_array);
}
switch($dest){
case 'NULL':{
redirect('home','refresh');
break;
}
case 'part1':{
redirect('subhome','refresh');
break;
}
case 'part2':{
redirect('subhome1','refresh');
break;
}
default :{
redirect('mainhome','refresh');
break;
}
}
return TRUE;
}
else
{
$data['msg'] = "Something Wrong Username/Password";
$this->load->view('login',$data);
//return false;
}
}
};
?>
The problem is that you are passing $dest to the index() function but you are attempting to use it in your check_database() function. So either you want to move your switch into the index function or you want to pass $dest to check_database() like
function check_database($dest)
{
//You can use $dest in here
}
If you want to pass an extra parameter to your callback function you need to put it in brackets like
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database[parameter]');
or
$this->form_validation->set_rules("password", "Password", "trim|required|xss_clean|callback_check_database[$parameter]");
Hello all, this is my first CI project.
I have a simple form validation function in my model.
function verify_login()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
var_dump($this->form_validation->run());
die;
if ($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to login page
$this->load->view('login_view');
} else {
//Go to private area
redirect('home', 'refresh');
}
}
This only works when it's in a controller but not in a model. When I try passing the variables from the controller to the function in the model, the variables get received but won't process.
Can someone enlighten me? Thank you.
its fine to do your form validation in a model. But you want to have the validation return True or False to your controller. Not call a view. So like
// in your Model lets call it Users
function verify_login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run() == FALSE) {
return FALSE ;
} else {
return TRUE;
}
}
// Your callback function
// in Controller
function verify(){
if( $this->users->verify_login() == FALSE ){
// $this->errormessage will be available in any view that is called from this controller
$this-errormessage = "There was an error with your Log In. Please try again." ;
$this->showLogin() ; }
else {
// set a session so you can confirm they are logged in on other pages
$this->setLoginSession($this->input->post('username', TRUE)) ;
$this->showUserHome(); }
}
Another thing to think about -- often people know their user name but mess up their password. So if you check for them separately you can adjust the error message accordingly. And if you check for user name and there are no results -- you don't need to check for password and in the error message you can tell them there is no user by that name.
My biggest recommendation to you is to not do validations like this in your model. If you're validating in your model it needs to be against a database value directly and not a form.
Please let me know if that solves your problem, if not please comment and I'll edit my answer.
UPDATE: Please ignore some of the above, as I was going off theory and not fact :)
I'll have to dig deeper into the CI core to get a good idea of what's wrong with this. Your code itself looks ok. Only thing I can see is that your callback may not exist in your model and only in your controller. Echoing the below I do not consider this a good use of the model.
The docs on validations
class Data_model extends CI_Model
{
public function rules()
{
return [
['field' => 'pertanyaan',
'label' => 'pertanyaan',
'rules' => 'required|is_unique[data.pertanyaan]'],
['field' => 'jawaban',
'label' => 'jawaban',
'rules' => 'required']
];
}
}
class Datas extends CI_Controller
{
public function add()
{
$data = $this->data_model;
$validation = $this->form_validation;
$validation->set_rules($data->rules());
if ($validation->run()) {
$data->save();
$this->session->set_flashdata('success', 'Berhasil disimpan');
}
$this->load->view("admin/data/new_form");
}
}
I have this controller set up for a login:
<?php
class Login extends Controller {
function __construct() {
parent::Controller();
$this->form_validation->set_error_delimiters('', '');
$this->output->enable_profiler(TRUE);
}
function index(){
redirect('/login/terminal');
}
function terminal() {
// terminal login
$this->form_validation->set_rules(array('username','password'), 'Username', 'callback_terminal_login_check[$username,$password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_header');
$this->load->view('login_terminal');
$data['version'] = $this->master->GetVersion();
$this->load->view('login_footer', $data);
} else {
redirect('/terminal');
}
}
function terminal_login_check($username,$password) {
// callback function to perform terminal login
if ($this->authentication->DoTerminalAuthentication($username,$password)) {
echo $username;
return TRUE;
} else {
$this->form_validation->set_message('terminal_login_check', 'Invalid');
return FALSE;
}
}
}
What I am looking at is the line that does the form validation callback >> $this->form_validation->set_rules(array('username','password'), 'Username', 'callback_terminal_login_check[$username,$password]');
I know this is not right. Basically what I want to do is check the username and password against the Authentication->DoTerminalAuthentication model to process the user's login. I want to pass the $username and $password form fields. Here is my form view if it helps:
<div id="title">Terminal Login</div>
<?php
if (validation_errors()) {
echo '<div id="error">' . validation_errors() . '</div>';
}
?>
<?=form_open('login/terminal');?>
<?=form_label('Username', 'username')?><br />
<?=form_input(array('id'=>'username','name'=>'username','value'=>set_value('username')))?><br />
<?=form_label('Password', 'password')?><br />
<?=form_password(array('id'=>'password','name'=>'password'))?><br />
<?=form_submit(array('name'=>'passwordsubmit','value'=>'Login >>'))?><br />
<?=form_close();?>
Use this in your controller to set your validation rules.
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|callback_terminal_login_check');
And a callback something like this. I'd use a model if you are comparing your post data to a database.
function terminal_login_check()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
// LOAD MODEL HERE
if ($this->authentication->DoTerminalAuthentication($username, $password))
{
echo $username;
return TRUE;
}
else
{
$this->form_validation->set_message('terminal_login_check', 'Invalid');
return FALSE;
}
}
Edit 2013-07-09: Added required field to password validation rule so you don't have to hit the DB if someone doesn't add a password.
As I understand it, form validation works on a field by field basis. To achieve what you want, I would attach the callback to one of the fields (probably the password field would be best) and then access the other form field data using the global POST array. This way you don't need to pass anything to the callback function as parameters.
I prefer to use form validation for simple input validation like checking for empty fields, invalid email addresses, too short passwords etc. I tend not to use form validation for more complex logic like authentication. I'd put the authentication check in the action method rather than in a validation callback function. It would get past your particular problem by side-stepping it.
function terminal()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run())
{
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->authentication->DoTerminalAuthentication($username, $password))
{
// Handle successful login
}
else
{
// Authentication failed. Alert the view.
$this->load->view('terminal', array('login_failed' => true));
}
}
else
{
$this->load->view('terminal', array('login_failed' => false));
}
}
And then in the view you can place this below your login form
<?php if ($login_failed) : ?>
<span id="login-failed-message">Login failed</span>
<?php endif; ?>