codeigniter print form specific validation error - php

I have 2 forms on a page eg: 'create_user' and 'update_user' i want to show validation errors specific to each form just above the form. i mean, i want to show validation errors for 'create_user' form just above it and same for 'update_user'.
Right now if i submit update, form errors are showing above both of the forms.
is there something like
<? echo validation_errors("create_user"); ?>

You could do something like:
//pass validation_errors as data to your view from your controller, like
//in your controller
if ($this->form_validation->run()) { //form create_user form
//process
}
else {
$data['create_user_form_errors'] = validation_errors();
}
//and for second form update_user
if ($this->form_validation->run()) { //form create_user form
//process
}
else {
$data['update_user_form_errors'] = validation_errors();
}
//then in your view
if (isset($create_user_form_errors)) echo $create_user_form_errors; //show above first form
//and
if (isset($update_user_form_errors)) echo $update_user_form_errors; //show above second form
Something like that should work for showing errors based on multiple forms. Hope it helps

Simplest way is this:
Pass some sort of form-identifying hidden field with each form
Pass that same hidden field to the view error state, and use a basic IF condition to run validation_errors() in the correct location
You could probably extend the validation class somehow to do what you're asking, but it would be a very specific implementation, and hardly useful in a framework (which is why CI doesn't "know how" to do this by default). The added complexity of working with the extended class would likely counteract any benefit of not simply using basic logic in the view.

Related

Codeigniter controller prevent entire page from reloading when form is validating

Basically, I have my controller function for adding in my case a page but let’s focus on the function:
public function add() {
$this->session->unset_userdata('postID');
if ($this->form_validation->run() == TRUE) {
// Form Validation
}
$this->data['subview'] = 'blah blah';
$this->load->view('blah blah.php', $this->data);
}
Basically when the form is submitted it will still unset the postID in this case, however i want to ensure that if the form is submitted and there are errors that this is missed and it doesn’t redo some of my functions and variables. This is happening for a lot of my content when the form is submitted it re-initiates variables that i want to be ignored.
I also tried the following but it didn’t work either:
if (!$this->form_validation->run()) {
$this->session->unset_userdata('postID');
}
How do i avoid the entire page being redone when the form is validating as it re-performs all the page load content?
Thanks
You can check if the submit button was pushed by using
if($this->input->post('the-name-of-the-submit-button')) {
$this->session->unset_userdata('postID');
}
Basically, $this->form_validation->run() checks if the form was submitted and if it passed validation rules, whereas the above simply checks if the form was submitted at all.
You need to do an ajax submission if you don't want the page to refresh:
http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/
Alternatively, you can fill in the field values so they don't "RESET", ie <input value="<?php echo $_POST['value'];?>" />, but ajax is a much better solution.
You can return errors in JSON from your codeigniter controller and display them on your page.
If you do any type of request with your browser, the page is always going to refresh, unless you use ajax/javascript.

How to add a unique message on page redirect using PHP

I know this question is simplistic, I am still learning.
I am trying to determine wether a user has filled out a form. The form submits to a function.
The function looks like this:
if(isset($_POST['register'])) {
$newuser_values = $_POST['register'];
foreach ($newuser_values as $key => $value) {
if("" == trim($value])){
.....
}
}
}
'register' is an array of values from the form.
I am trying to decide what to put inside the ....
I know I want to redirect to the form but I would like to somehow pass along a message to the form and display it so that the user will know what was wrong. What strategy do I use?
Thanks in advance.
(1) You should put HTML form and PHP code on same file. Then,
You can do it by just echo "Enter value"; inside if block... But your this PHP code should be at position where you want to display the error msg.
OR
Store error msg in a var: $err="Enter value";
And then write <?php if(isset($err)) echo $err; ?>, where you want to display error.
(2) The approach above works when your HTML form and form processing PHP code (you mentioned above) should be on same coding file.
If you have two different file and want to redirect to the HTML form page with error msg then:
There are many methods, but easiest is, write header("location:formPageName.**php**?err=Enter Value"); inside if-block. [PHP code should be on top of page]
Then on formPageName.html write <?php if(isset($_GET["err"])) echo $_GET["err"]; ?>, where you want to display the error.

Codeigniter - handle form submission from different controller action

Whats the best way to handle the following situation in codeigniter:
Home controller has an index action and a submit action.
The submit action is used for a form submission. I want to load the page through the index controller though - including after form submission i.e. with form errors data to repopulate form inputs on error etc.
Whats the best way to do this - without having the index controller handle the main page loading and the form submission.
If you redirect(), you won't be able to use set_value() for re-populating your form fields.
What's easiest is having your index controller handle both the default load behavior, and the submission.
function index()
{
if($this->input->post('foo'))
{ // something was POSTed
$this->load->library('form_validation');
//validation rules
} else
{ // normal view
//
}
$this->load->view('home');
}
Alternatively, you can just set up your index and submit controller, and have them point at the same view, which detects if validation_errors() are set and re-populates form fields accordingly.
Third option (hackish): you could use flashdata to keep submission errors and the submitted form values across a redirect back to index. Something like this would work:
$this->session->set_flashdata('errors', $validation_errors());
Simply point your form at your submit action:
<form method="post" action="/home/submit">
Then, use the submit action to validate your input before redirecting back to the index action.

Can I submit a form and add record to DB by only php in the same file without using Get/Post methods?

Say I have create a registration form. Now to add records into a DB, we send the data to another php file by POST method, where we do some validations and add a record. Is it possible to do it in the same file without sending and getting the data by POST/GET? If no, then why?
EDIT: Even sending to the same php file is SENDING and losing resource. I ask this question because I want to avoid the lost of time on sending by GET/POST and getting by the same Get/POST. And if it is not posible, I want to understand why PHP does not allow.
No. You always have to send data from the client to the server, there is no way around that.
If you dont want to reload the entire page the user is on, you could submit the data via AJAX to the php file responsible for processing it and adding the data. That way the user never leaves the page.
yes ofcourse.
just in your form "action" put
$_SERVER['PHP_SELF']
then in the beginning of your PHP page check if the $_POST is set or not
if(isset($_POST))
{
// actions to be taken after form submission
}
ofcourse you can add a hidden input tag for refining checks for the $_POST. eg in your form
<input type="hidden" name="formSubmit" value="yes" />
then your check should be like
if(isset($_POST['formSubmit']))
{
// actions to be taken after form submission
}
It's possible. For example:
<?php
if(true === isset($_POST['submit']) // check if submit-button was clicked
{
// do some validation here...
// If validation successes add record into db here...
}
else // no post data sent so output the form
{
// output the form here...
}
Yes it is possible set
action="same page"
in form tag.
you can access your all form attributes on same page.
Yes it is easy. The form can post back to its self. This is most easily done by not even specifying the value of action in the form tag.
<form method='POST'>
Then at the top of the page before any content is put on the page, include an if statement to check if the form was submitted.
if (isset ($_POST['post'])) { // 'post' is the name of the submit button
$error = false;
// Do validation
From there do validation and act according to the result.
If you have lots of validation to do, perhaps put that in another file and include it.
include "formValidation.php";
If all is well and all tests are passed use
if ($error === false) {
Header ("Location: confirmation.php");
exit;
}
}
If tests fail, stay on the page keeping all the post data, and display an error.
if (isset ($error) && !empty ($error)) {
echo "<div class='error'>$error</div>";
}

form validation without reset

Is there a way to check the data sent by a form to a PHP page return to the form page WITHOUT resetting the data sent and show a error?
The form has 20 fields and I need to check one of them on a bd. If it fails the user may be redirected to the form page with the form populated and displaying a error message on the field which is 'wrong'.
I would like any advice of a technique instead of populating each field using PHP.
UPDATE:
I do not want to use any solution that involves repopulate the fields by myself!!!
I want a solution that return to the form page populated with the previous values. I've tried something like js.history.back or window.back(). But the form returns empty...
UPDATE: If you are looking for this type of behavior, nowadays there are several different techniques to achive this. I'm currently using jQuery (Ajax).
In your form fields HTML, add posted values as field value.
e.g:
<input type='text' name='email' value='<?php echo $_POST['email']; ?>' />
Yeah, just check the forms beforehand, make sure you run the form HTML after the validation procedure, and if validation fails, reload the form with all of the prior information in the fields.
It might look something like this:
<?php if(isset($_POST['submit']){
// validation code goes here with a trigger variable to
// contain true or false depending on the outcome
}
if($trigger==false){
// load up your post data here
}
echo '
<!-- form HTML goes here -->
';
On your Form Validation page
<?php
$form_values = $_POST;
//Your Form Validation
//$form_validated = TRUE/FALSE; // FALSE if there were errors
if ($form_validated) {$form_values = array();}
$_SESSION['form_values'] = $form_values; /* if your form validation page and form page is not on the same page and can also use the same technique for error messages */
?>
On your Form page for each input field.
<?php
$form_values = $_SESSION['form_values']; //if your form validation page and form page is not on the same page
unset($_SESSION['form_values']);
echo '<input type="text" name="user_name" value="'.$form_values['user_name'].'" />';
?>
Different input types will need to handle the $form_values array differently but this should get your started.
If you are not using a seperate form validation page, you can get the form values directly form the $_POST array.

Categories