Submitting form to itself and echoing validation errors in CodeIgniter - php

I had few forms in my project, they were submitted to public function's like site.com/email => site.com/validate_email, but then I realized that that's not what I want.
Now I need to make them submit to themselfs ,check and display validation errors.
What is the appropriate way to do this? Check for emptyness of $_POST and then call my new _validate_email(//that will return true or false) if post isn't empty?
Or something else not that noobish?:)
for example:
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim|xss_clean|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run())
{
//some stuff here
}
else
{
$this->load->view('login'); //or redirect()?
}
view:
<?php $this->load->view('header'); ?>
<div class="form-container">
<?=$this->form_validation->validation_errors();?>
<?php
$form_atr = array(
'id' => 'form-set'
);
echo form_open('main/login_validation', $form_atr);//this should be 'main/login'
?>
<div class="header">
/*
here goes other parts of form
*/
</div><!--END form-container -->`
<?php $this->load->view('footer'); ?>
So, basicaly i need to combine login() and login_validation(), but make it so that when user`s input incorrect i get reloaded page of the same view with the same URL and get validation errors displayed.
I've tried to put code of validation into the same function that displays form, but I can't figure out how to redirect or reload the view to show val.errors if any.

So, I think this way is correct(It really should be):
I made my login_validation() private by adding '_' before it, like so _login_validation()
Than I added an if() statement that contains $_POST form variables and i am cheking them with php isset() function, that way the code can determine when user submitted a form. And after all that I just call _login_validation() if inputs are set or load again my login view if not.
public function login()
{
if(isset($_POST['password']) && isset($_POST['email']))
{
$this->_login_validation();
}
else
{
$this->load->view('login');
}
}
and dont forget to process your form so it would submit to the same URL:
echo form_open('', $form_atr);
Hope that will help someone someday.

First of all, validation_errors() is one kind of flash data, so whenever you redirect the page with error the validation errors will be displayed, if you reload it second time it will not be displayed.
From your question i could not understand, do you want to show the errors or not.
if you want to show the errors:
then just redirect the page to login and in the login view add a alert div.
if you don't want to show the errors:
then just remove the alert div.
*i don't see any alert div in your login view, if validation errors are still displayed then may be alert div is in the header view

Related

CodeIgniter - Controller - loading view with template

I have a template design for each page and it is working without any issues, now i have a problem with form validation and template.
my_controller //inside my controller
function __construct()
{
parent::__construct();
$this->load->library('template');
}
public function page1(){
$this->template->write('title', 'COMPANY');
$this->template->write_view('content', 'company');
$this->template->render();
}
public function validation(){
//for page1 form validation
//form validation here
if ($this->form_validation->run() == FALSE){
// here i need to call my page1 again to update the form error
// option1: $this->load->view('page1'); // this is just loading page1, not loading with my template, template file has header, footer, js and css file includes
// option2: $this->template->load('template', 'page1'); // it is loading page withing page
// option3: $this->template->write_view('content', 'page1');
// $this->template->render(); // this is same as option2
} else {
$this->load->view('formsuccess');
}
}
So my question is how do i can call same view (within one controller) for multiple time when it is already loaded with template?
EDITED for more clarity
My template file is just single file ( not separated like header, footer) will have all header information and footer information with common style sheet and script files.
I am having
<?php $content ?>
variable name inside the template to pass my content from controller.
for example see my page1 function(),
$this->template->write('title', 'COMPANY'); // to write a value on variable
$this->template->write_view('content', 'page1'); //view page to write on template
$this->template->render(); // final template render
This page is having form validation, if my form validation is FALSE, how do i can reload the template page with validation error?
I have tried so many way, please check my option1, 2, 3, i never got a solution to solve this, now please tell me how do i can solve this?
If I understand correctly, you want to display the validation errors?
Inside your View file, put the following:
Short IF-Statement Form:
<?php if ( validation_errors() ) :?>
<div>
<?php echo $validation_errors();?>
</div>
<?php endif;?>
Regular If-Statement Form:
<?php if ( validation_errors() ) {?>
<div>
<?php echo $validation_errors();?>
</div>
<?php }?>
Validation Errors Doc

Codeigniter - add method URL & Redirect issue

I have a method in CI which basically adds a user to a table - if any form validation occurs it reloads the view - if successful it reloads the view to show that the user was added successfully. As seen below:
public function loadPeopleView(){
//loads unit page view
$this->load->model('people_model');
$people['people'] = $this->people_model->getPeople();
$this->load->view("header");
$this->load->view("people page/people_view", $people);
$this->load->view("footer");
}
public function addPerson(){
$this->form_validation->set_rules('personName', 'personName', 'required|min_length[6]|max_length[150]|trim|xss_clean');
$this->form_validation->set_rules('personPet', 'personPet', 'required|trim|min_length[3]|max_length[30]|xss_clean');
if($this->form_validation->run()){
$this->load->model('');
$this->people_model->addPerson();
$this->loadPeopleView();
} else{
//if validation fails - returns the peopl view this display error messages
$this->loadPeopleView();
}
}
my issue is when someone adds a person the browser remains on:
localhost/peoplecontroller/addperson
if the user keeps refreshing the page - loads of people will continue to be added in - is there anyway I can put the page back to:
localhost/peoplecontroller/
without having to use a redirect as I still want any error messages from the form validation to appear
I am only giving you an example please arrange according save and return functionality
public function addPerson(){
$this->load->model('people_model'); // load model
// validation
$this->form_validation->set_rules('personName', 'personName', 'required|min_length[6]|max_length[150]|trim|xss_clean');
$this->form_validation->set_rules('personPet', 'personPet', 'required|trim|min_length[3]|max_length[30]|xss_clean');
// check validation not clear
if ($this->form_validation->run() == FALSE) {
//if validation fails - returns the peopl view this display error messages
// also set error dat back
// setting up send back values to view
$this->data['personName'] = $this->input->post('personName');
$this->data['personPet'] = $this->input->post('personPet');
// get this->data values as a variable in view like $personName
// load view
$this->load->view("header");
$this->load->view("people page/people_view", $this->data);
$this->load->view("footer");
}
else{ // after validation success
// do your saving db stuff and set success message in session flash and redirect to
$this->people_model->addPerson();
// get and show message flash in your view
$this->session->set_flashdata('message', 'Please check card details and try again');
redirect('results', 'refresh');
}
}

How to get Detail view of bootstrap html form after submit Codeigniter

I have a bootstrap form where after filling data its successfully get inserted to database .Now i want to show detail view of form with filled data but it taking me back to create view after submit with data added to database. i guess i have problem with site url. for better understanding hereby i am attaching my code.
my create view file code is :
<form class="form-horizontal" id="job" action="<?php echo site_url('admission/add_students')?>" method="POST" name="job">
where as controllers(admission):
function add_students() {
$this->load->model('admission_detail_model');
$data=array(
'student_id'=>'La-0002'.$this->input->post('student_id'),
'father_name'=>$this->input->post('father_name'),
'mother_name'=>$this->input->post('mother_name'),
'fname'=>$this->input->post('first_name'),
'lname'=>$this->input->post('Last_name'),
'place_of_birth'=>$this->input->post('place_birth'),
'mother_tounge'=>$this->input->post('mother_tounge'),
'd_o_b'=>$this->input->post('DOB'),
'nationality'=>$this->input->post('nationality'),
'religion'=>$this->input->post('religion'),
'sc_st_obc'=>$this->input->post('sc_st_obc'),
'caste'=>$this->input->post('caste'),
'address'=>$this->input->post('address'),
'admitting_student'=>$this->input->post('Admit_std'),
'father_edu_qual'=>$this->input->post('father_q'),
'mother_edu_qual'=>$this->input->post('mother_q'),
'annual_income'=>$this->input->post('annual_income'),
'father_occupation'=>$this->input->post('father_occupation')
);
$this->admission_detail_model->add_students($data);
$this->index();
}
Model:
class Admission_detail_model extends CI_Model {
function add_students($data) {
$this->db->insert('students',$data);
return; }
Everything working fine i just want to add detail view after submit form not another create form View. For detail view i have controller defined in my base controller(admission) :
public function detailed_admission()
{
$this->load->helper('url');
$this->load->view('Header');
$this->load->view('side_menu');
$this->load->view('admission/detailted_view');
$this->load->view('footer');
}
when i try to replace site url in create view file
"<?php echo site_url('admission/detailted_view')?>"`
it does not enter data in database redirect directly to this view without any data.
This is my first question so if i had made any mistake please avoid it.
Thankyou for helping
Check my comments in the code.
function add_students() {
$this->load->model('admission_detail_model');
$data=array(
'student_id'=>'La-0002'.$this->input->post('student_id'),
'father_name'=>$this->input->post('father_name'),
'mother_name'=>$this->input->post('mother_name'),
'fname'=>$this->input->post('first_name'),
'lname'=>$this->input->post('Last_name'),
'place_of_birth'=>$this->input->post('place_birth'),
'mother_tounge'=>$this->input->post('mother_tounge'),
'd_o_b'=>$this->input->post('DOB'),
'nationality'=>$this->input->post('nationality'),
'religion'=>$this->input->post('religion'),
'sc_st_obc'=>$this->input->post('sc_st_obc'),
'caste'=>$this->input->post('caste'),
'address'=>$this->input->post('address'),
'admitting_student'=>$this->input->post('Admit_std'),
'father_edu_qual'=>$this->input->post('father_q'),
'mother_edu_qual'=>$this->input->post('mother_q'),
'annual_income'=>$this->input->post('annual_income'),
'father_occupation'=>$this->input->post('father_occupation')
);
//To insert the record in the database
$this->admission_detail_model->add_students($data); after
//open the detail view page
// $this->index(); why did you call index function ??
$this->detailed_admission(); //call detailed function just after the form submission or you can perform redirect('admission/detailed_admission')
}

Laravel show errors in view

if my validation fails I do this:
return Redirect::back()->with('validation', $validation->errors->all());
also I am using:
$restful = true;
so when I am on get_edit() - I'am getting an error that there are no $validation variable when generating my view, when in post_edit() - its all okay because its returns a redirect with errors...
this is my view:
<? foreach($validation as $e): ?>
<div><?= $e; ?></div>
<? endforeach; ?>
undefined variable $validation, right now I'am trying to put it on the Router::before
Route::filter('before', function()
{
View::share('validation', array());
});
so the variable exists but is empty, but now arises a new problem, everytime after this filter executes it overrides those $validation that generates my post_edit(), also i've seen a variable $errors in my view but is ever empty, i don't how to use it, can you help me?
so shortly my problem is:
public function get_edit($id)
{
//generate my view with all nessesary data, but i can't generate here an error variable
// or its better to put it in one place to globally share it in the views, otherwise i am //getting an error
}
public function post_edit($id)
{
//validating $_POST data, if there is an error redirect it back to the get_edit() WITH a //variable containing errors
}
Did you read the docs? http://laravel.com/docs/5.0/validation#error-messages-and-views
You can use return Redirect::back()->withErrors($validation);
In your views, you can always use redirect('register')->withErrors($validator)$errors, without binding them to the view.

Codeigniter Ocular and Form Validation

New to CodeIgniter and new to Ocular so bear with me.
I used to code in the following way when running form validation (where the index() method contains the form loading code):
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
$this->load->view('view_name', $data);
}
However I'm now trying to use the Ocular Template Library and the above code no longer works see example below:
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
$this->template->set($data);
$this->template->render();
}
The above code does not run through the index method as it used to without Ocular and I was wondering what the best practice is to correct this or even if my previous code was best practice?
Regards,
Numan1617
Sometimes it's hard to determine best practice with Codeigniter because it's convention-less nature, so all I can really tell you is how I've found best in my experience...
I assume you're form view is being served up via index() and then you're submitting your form to this (seperate) controller function that validates and processes the form data, and re-displays the view with errors if there was a problem...
I would clean this up by consolidating it all into a single function...
public function form()
{
//if this is a post request
if ($_POST)
{
//check the validation
if ($this->form_validation->run())
{
//process it
//and then redirect if you want to send to a "success" page
redirect('uri/to/success');
}
else
{
//load up $data values to re-display form
}
}
//load up any $data values needed for standard view
$this->load->view('view', $data);
// or $this->template stuff...
}
It always seemed to me to be a bad route to go down calling controller functions internally, ex. $this->index()

Categories