retaining data entered by user in the form - codeigniter

I am using codeigniter. Below is the code for my registration page.
Controller
function register()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|is_unique[users.username]');
$this->form_validation->set_rules('user_email', 'Email', 'trim|required|valid_email|is_unique[users.user_email]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('ans_1', 'Security answer 1', 'required');
$this->form_validation->set_rules('ans_2', 'Security answer 2', 'required');
if($this->form_validation->run() == FALSE) {
//not validated - reload the view and display errors
$this->load->database();
$this->load->model('user');
$data['ques'] = $this->user->get_que();
$this->load->view('register',$data);
}
else {
$this->load->database();
$this->load->model('user');
//create user
$this->user->create_user();
$this->thank();
}
}
View
<!DOCTYPE html>
<html>
<head>
<title> Login</title>
<link rel="stylesheet" href="http://localhost/cinema/assets/css/form.css">
</head>
<body>
<form action="http://localhost/cinema/login/register" method="post" accept-charset="utf-8" class="username register" >
<h3>User Registration form:</h3>
<p><label for="first_name">First Name</label>
<input type="text" name="first_name" /></p>
<p><label for="last_name">Last Name</label>
<input type="text" name="last_name" /></p>
<p><label for="username">Username</label>
<input type="text" name="username" /></p>
<p><label for="user_email">Email</label>
<input type="text" name="user_email" /></p>
<p><label for="password">Password</label>
<input type="password" name="password" /></p>
<br><font size='4'>Select security question 1:</font>
<select name="que_1">
<?php
foreach($ques as $que)
{
echo '<option value="'.$que->que_ID.'">'.$que->que.'</option>';
}
?>
</select><br><br>
<p><label for="ans_1">Answer:</label>
<input type="text" name="ans_1" /></p>
<br><font size='4'>Select security question 2:</font>
<select name="que_2">
<?php
foreach($ques as $que)
{
echo '<option value="'.$que->que_ID.'">'.$que->que.'</option>';
}
?>
</select><br><br>
<p><label for="ans_2">Answer:</label>
<input type="text" name="ans_2" /></p>
<input type="submit" name="btnSubmit" class="styled-button-8" style="float:right; margin-right:300px; margin-top:-10px;" value="Sign Up!"
/>
<font color="red" size="4"><b>
<?php echo validation_errors(); ?></b></font>
</form>
</body>
</html>
<br>
My problem is that in case the user fills invalid data and clicks the signup button, the page is refreshed and the validation errors are displayed but the data entered by the user doesn't remain there.He has to again fill the whole form. I want the user data to be retained and displayed in this case. Thanks in advance .. :)

For this you need set_value()
For input fileds
<input type="text" name="last_name" value='<?php echo set_value('last_name')?>'/>
This will get the value from $_POST and print after failed validation. Also takes 2nd parameter as default value.
<?php echo set_value('last_name','John')?>
Read the Form Helper Class.

You can try like this. You can maintain session to display user fields data while validation check. I added a Sample with session in your form.
Your View :
<?php session_start(); ?>
<form action="http://localhost/cinema/login/register" method="post" accept-charset="utf-8" class="username register" >
<h3>User Registration form:</h3>
<p><label for="first_name">First Name</label>
<input type="text" name="first_name" value="<?php echo $_SESSION['first_name']; ?>" /></p>
<font color="red" size="4"><b>
<?php echo validation_errors(); ?></b></font>
</form>
Your controller:
function register() {
$this->load->library('form_validation');
$firstName = $this->form_validation->set_rules('first_name', 'First Name', 'trim|required');
$this->session->set_userdata('first_name', $firstName);
if ($this->form_validation->run() == FALSE) {
//redirect to register page
} else {
//register user details
$this->session->unset_userdata('first_name');
}

Better solution is : use post data
<input type="text" name="last_name" value='<?php echo $this->input->post('last_name')?>'/>
When you use set_value(), you must send that field to validation even it is not required.
But for Post, you don't want to do any additional work.

In your controller put a data array and pass the user entered values to that.Then if there are form validation errors pass those data to the view.
In the view use CI set_value() method to show the previous entered values.

Related

ajax form display message

i have a form that insert in dbase what i write
here is the form,
<form id="contact-form" class="bl_form text-center" action="<?php echo "index.php?page=rooms&room=$rid&rpw=$rpw&r=$r";
?>" method="post" novalidate>
<span class="field-wrap scrollimation fade-right">
<input type="hidden" id="contact-name" name="contactName" type="text"
class="label_better requiredField" data-new-placeholder="Name" placeholder="Name" value="<?php echo "$uid"; ?>" data-error-
empty="*Enter your name">
</span>
<span class="field-wrap scrollimation fade-left">
<label class="control-label" for="contact-message">Message</label>
<textarea id="contact-message" name="message" rows="1" class="label_better
requiredField" data-new-placeholder="Message" placeholder="Message" data-error-empty="*Enter your message"></textarea>
</span>
<p class="text-center"><button name="sy2" id="submit_post" type="submit" class="btn btn-meflat
icon-left" data-error-message="Error!" data-sending-message="Sending..." data-ok-message="Message Sent"><i class="fa fa-paper-
plane"></i>Send Message</button></p>
<input type="hidden" name="submitted" id="submitted" value="true" />
<?php echo "<postfield name=\"message\" value=\"$(message)\"/>"; ?>
</form>
and i want to put a ajax code that display this message from dbase
<?php echo make_clickable($tosay)."$link_delete"; ?>
Can someone provide me an example?Thank you
Look at this
Ajax tutorial for post and get
So, the jQuery
$('body').on('submit', '#contact-form', function(){
$.post({$(this).attr("action"), $(this).serialize(), function(data){
if(data){
alert(data.message);
}
}, 'json');
return false;
});
And the server side
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// do your thing here
echo json_encode(array("message" => make_clickable($tosay).$link_delete));
die();
}
?>

Unresponsive form submit button in my CodeIgniter

I am trying to get to know CodeIgniter. I just couldn’t figure out what the problem with the code below is. However, when I click on the ‘submit’ button, nothing happens. I mean no record is inserted in the database table.
The php in the view is as follows.
<?php echo form_open('site/create'); ?>
<?php echo form_close();?>
<p>
<label for="title">Title</label>
<input type="text" name="title" id="title" />
</p>
<p>
<label for="content">Content</label>
<input type="text" name="content" id="content" />
</p>
<p>
<input type="submit" value="submit" />
</p>
Down goes the controller
<?php
class site extends CI_Controller
{
function index()
{
$this->load->view('options_view');
}
function create()
{
$rec=array(
'title' => $this->input->post('title'),
'content'=>$this->input->post('content')
);
$this->site_model->add_record($rec);
$this->index();
}
}
?>
And the model is as follows.
<?php
class site_model extends CI_Model
{
function get_records()
{
$query=$this->db->get('other');
return $query->result();
}
function add_record($rec)
{
$this->db->insert('other',$rec);
return;
}
function update_record($rec)
{
$this->db->where('id',2);
$this->db->update('other',$rec);
}
function delete_rec()
{
$this->db-delete();
}
}
?>
The form close has to be at the end:
<?php echo form_open('site/create'); ?>
<p>
<label for="title">Title</label>
<input type="text" name="title" id="title" />
</p>
<p>
<label for="content">Content</label>
<input type="text" name="content" id="content" />
</p>
<p>
<input type="submit" value="submit" />
</p>
<?php echo form_close();?>
It's better and easier to use the form library from codeigniter.
I believe you must be familiar with Html already to start using codeIgniter so this should be easy... Like all html forms you need to have an opening tag and a closing tag, what you have done is open and close the form at the top before the other elements. So as expected, the submit button wont do what you need it to do. The solution is to move
<?php echo form_close();?>
to the bottom so your code appears as such
<?php echo form_open('site/create'); ?>
<p>
<label for="title">Title</label>
<input type="text" name="title" id="title" />
</p>
<p>
<label for="content">Content</label>
<input type="text" name="content" id="content" />
</p>
<p>
<input type="submit" value="submit" />
</p>
<?php echo form_close();?>
All the best.

Form not validated

I want to validate a form that has two fields, username and password. When I insert data CodeIgniter show the error message, though I insert correct data.
The view:
<div id="acformulario">
<?php echo validation_errors(); echo form_open('cindice/valida');?>
<label for="correo" id="dcorreo">Dirección de correo</label>
<input type="text" name="drcorreo" id="dcc"/><br /><br />
<label for="contrasenya" id="cont">Contraseña</label>
<input type="password" name="contrasena" id="cmcont"/><br /><br />
<!--<label for="enviar"></label>-->
<input type="submit" name="envia" id="bentrar" value="Entrar"/>
</form>
</div>
The controller:
public function valida()
{
$this->input->post('drcorreo');
$this->input->post('contrasena');
$this->form_validation->set_rules('correo','Dirección de
correo','trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('contrasenya','Contraseña',
'trim|required|md5|xss_clean');
if ($this->form_validation->run()==true)
{
echo ("correct");
}
else {
echo ("wrong");
}
}
When I typed correct or wrong data any message of rules is displayed. For example, both fields are required, but if I click the submit button with empty fields I watch wrong on the screen, and I should watch username is required.
what's wrong?
Thanks.
first of all you got your names mixed up codeingiters form validation uses the name of the input type as the parameter and not the label.
if your input name is drcorreo
then on your set_rules use
set_rules('drcorreo','Dirección decorreo','trim|required|valid_email|xss_clean');
where the first parameter is the name of the input field
$this->form_validation->set_rules('drcorreo','Dirección de
correo','trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('contrasena','Contraseña',
'trim|required|md5|xss_clean');
Change Your first parameter Of set_rules Method..It Takes name Of the input.
The code updated:
view:
<div id="acformulario">
<?php echo validation_errors(); echo form_open('cindice/valida');?>
<label for="correo" id="dcorreo">Dirección de correo</label>
<input type="text" name="drcorreo" id="dcc"/><br /><br />
<label for="contrasenya" id="cont">Contraseña</label>
<input type="password" name="contrasena" id="cmcont"/><br /><br />
<input type="submit" name="envia" id="bentrar" value="Entrar" />
</form>
</div>
controller:
public function valida()
{
$this->input->post('drcorreo');
$this->input->post('contrasena');
$this->form_validation->set_rules('drcorreo','Dirección de
correo','trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('contrasena','Contraseña',
'trim|required|md5|xss_clean');
if ($this->form_validation->run()==true)
{
echo ("good");
}
else {
echo ("wrong");
}
}

Validation rules in CodeIgniter

I am trying to validate email and password using the CodeIgniter's form_validation library. But when I typed wrong email or password the error message of validation_rules is not displayed.
The controller:
public function anuncios()
{
$usr=$this->input->post('Usuario');
$this->input->post('Contrasenya');
$this->form_validation->set_rules('drcorreo','Nombre de usuario',
'trim|required|min_length[5]|xss_clean');
$this->form_validation->set_rules('contrasena','Contraseña',
'trim|required|min_length[8]|md5|xss_clean');
if($this->form_validation->run())
{
$this->load->model('modelo_usuarios');
if($this->modelo_usuarios->puede_entrar())
{
echo "Credenciales correctos";
$this->load->model("modelo_bd");
$data['vanc']=$this->modelo_bd->datos();
$this->load->view('vancios',$data);
return true;
}
else { //this one is never displayed
echo "Credenciales incorrectos";
echo "Usuario o contrasenya incorrectos<br /><br />";
$this->load->view('indice');
return false;
}
}
else { //this one is displayed but not the rules specified in
//form_validation_lang.php file
echo "Las reglas no son validas";
$this->load->view('indice');
}
}
View:
<div id="acformulario">
<form action="http://localhost/Pruebas/index.php/cindice/anuncios" method="post">
<label for="correo" id="dcorreo">Dirección de correo</label>
<input type="text" name="drcorreo" id="dcc"/><br /><br />
<label for="contrasenya" id="cont">Contraseña</label>
<input type="password" name="contrasena" id="cmcont"/><br /><br />
<!--<label for="enviar"></label>-->
<input type="submit" name="envia" id="bentrar" value="Entrar" />
</form>
</div>
Why error messages are not displayed?
Thanks.
i assume you call "form" helper in your autoload.php file,
use your view like this;
<div class="errors"><?php echo validation_errors(); ?></div>
<div id="acformulario">
<form action="http://localhost/Pruebas/index.php/cindice/anuncios" method="post">
<label for="correo" id="dcorreo">Dirección de correo</label>
<input type="text" name="drcorreo" id="dcc"/><br /><br />
<label for="contrasenya" id="cont">Contraseña</label>
<input type="password" name="contrasena" id="cmcont"/><br /><br />
<!--<label for="enviar"></label>-->
<input type="submit" name="envia" id="bentrar" value="Entrar" />
</form>
</div>
the point is "validation_errors()" function in here.
The 'can not enter' message is passed back after the rules have been passed. It is inside of the if statement when the form validation is true.
If you want this message to be displayed either load the message into the view, or set it as flash data.
Why not make the puede_entrar() model call into a custom callback form validation rule, then it can be added to the rules that are set.
Look here for information on custom callbacks.
This is how I would code your controller;
<?php
class Foo extends CI_Controller {
public function anuncios() {
// xxs_clean set globally in config
$this->form_validation->set_rules('drcorreo','Nombre de usuario', 'trim|required|min_length[5]|callback_puede_entrar');
// should use sha1 at least for hashing, see http://www.freerainbowtables.com/tables/
$this->form_validation->set_rules('contrasena','Contraseña', 'trim|required|min_length[8]|md5');
if($this->form_validation->run()) {
$this->load->model('modelo_bd');
$data['vanc']=$this->modelo_bd->datos();
$this->load->view('vancios',$data);
} else {
// redisplay form with validation errors
$this->load->view('indice');
}
}
public function puede_entrar($val) {
$this->load->model('modelo_usuarios');
if($this->modelo_usuarios->puede_entrar()) {
return TRUE;
} else {
$this->form_validation->set_message('puede_entrar', 'Las reglas no son validas.');
return FALSE;
}
}
}
The view (assuming you have autoloaded or have loaded $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); elsewhere);
<div id="acformulario">
<form action="http://localhost/Pruebas/index.php/cindice/anuncios" method="post">
<?php echo form_error('drcorreo'); ?>
<label for="correo" id="dcorreo">Dirección de correo</label>
<input type="text" name="drcorreo" id="dcc"/><br /><br />
<label for="contrasenya" id="cont">Contraseña</label>
<?php echo form_error('contrasena'); ?>
<input type="password" name="contrasena" id="cmcont"/><br /><br />
<!--<label for="enviar"></label>-->
<input type="submit" name="envia" id="bentrar" value="Entrar" />
</form>
</div>

passing array to view codeigniter

I have the problem of doing the validation of fields myself. Now there are 5-6 fields in the form. So I am checking each one in my controller, and if there is wrong i wish to load the view again and pass the error array to it.
I achieved the above functionality with this:
<html>
<head>
<title>My Form</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
</head>
<body>
<?php
echo $fullname;
?>
<?
echo form_open('/membership/register');
?>
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="cpassword" value="" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="" size="50" />
<h5>Mobile</h5>
<input type="text" name="mobile" value="" size="15" />
<h5>Home</h5>
<input type="text" name="home" value="" size="15" />
<h5>Full Name</h5>
<input type="text" name="fullname" value="" size="100" />
<br><br>
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
and in controller the code is:
if (preg_match('#[0-9]#',$fullname))
{
$errors['fullname'] = 'wrong name format!';
$this->load->view('register', $errors);
}
Now the real problem I have is if the many fields are wrong. I want to have $errors array passed to view and accessed there for all the values it contains. so I don't have to specify $fullname or $mobile to get the value. How can this be done? as to show the user everything missing in one go
First of all I advise using codeigniter's built in form validation class
Here is how I usually process my validation in the controller:
if ($this->input->post())
{
// process the POST data and store accordingly
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|xss_clean');
// the rest of your form fields validation can be set here
if ($this->form_validation->run() == FALSE)
{
// validation hasnt run or has errors, here just call your view
$this->load->view('same_view_file_with_the_form', $data);
}
else
{
// process the POST data upon correct validation
}
}
In my view file I call each error like this:
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<span class="error-red"><?php echo form_error("username"); ?></span>
<h5>Password</h5>
<input type="text" name="password" value="" size="50" />
<span class="error-red"><?php echo form_error("password"); ?></span>
<h5>Password Confirm</h5>
<input type="text" name="cpassword" value="" size="50" />
<span class="error-red"><?php echo form_error("cpassword"); ?></span>
Do all your checks in the controller prior to binding errors into the view.
e.g.
$errors = array();
if (preg_match('#[0-9]#',$fullname))
{
$errors['fullname'] = 'wrong name format!';
}
if ( do_something_to_validate(mobile) )
{
$errors['mobile'] = 'invalid mobile';
}
// after checking everything do this
$this->load->view('register', $errors);

Resources