passing array to view codeigniter - 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);

Related

duplicate insert after refresh page (iam new in developing with codeigniter)

i need to stop insert data when refresh page iam new in codeigniter and can't do redirect easly,please support
view:pages/home.php view which has a form
<html>
<head></head>
</body>
<?php echo validation_errors(); ?>
<?php echo form_open('speed/insert_to_db'); ?>
Branch: <input type="text" name="branch" /><br/>
Business Unit: <input type="text" name="buinessUnit" /><br/>
Device Type: <input type="text" name="deviceType" /><br/>
Brand: <input type="text" name="brand" /><br/>
Device Model: <input type="text" name="deviceModel" /><br/>
SN: <input type="text" name="SN" /><br/>
status: <input type="text" name="status" /><br/>
department: <input type="text" name="department" /><br/>
username: <input type="text" name="username" /><br/>
notes: <input type="textarea" name="notes" /><br/>
computername: <input type="text" name="computerName" /><br/>
Save:<input type="submit" name="save" />
</form>
</body>
</html>
model:add_model model which has insert_to_db function
public function insert_into_db(){
$post=$this->input->post();
$data=array('Branch'=>$post['branch'],'BusinessUnit'=>$post['buinessUnit'],'DeviceType'=>$post['deviceType'],'Brand'=>$post['brand'],'DeviceModel'=>$post['deviceModel'],'SN'=>$post['SN'],'Status'=>$post['status'],'Departmant'=>$post['department'],'UserName'=>$post['username'],'Notes'=>$post['notes'],'ComputerName'=>$post['computerName']);
$this->db->insert('hardware_assets', $data);
return $this->db->insert_id(); // if using mysql
}
}
controller:
<?php
class Speed extends CI_Controller {
function insert_to_db()
{
$this->load->model('add_model');
if($this->input->post('save')){
$this->add_model->insert_into_db();
$this->load->view('pages/home');//loading success view
}
}
}
I think you should try this in your controler:
function insert_to_db()
{
$this->load->model('add_model');
if( isset( $this->input->post('save') ) )
{
$this->add_model->insert_into_db();
//loading success view
$this->load->view('pages/home');
}
}

Submitting form action using javascript codeigniter

i have error for submitting form using javascript. the error said unknown column array. what is wrong with my array or maybe on my javascript.
this is my sample code.
<form action="">
<input type="text" name="name">
<input type="text" name="age">
<input type="button"onClick="this.form.action='<?php echo site_url('core')?>/'+'add_name';this.form.submit();" value="new"/>
</form>
WORKING WITHOUT JS
Try this:
<?php
$frmAttrs = array("id"=>"addFrm");
echo form_open('core/add_name', $frmAttrs);
?>
<input type="text" name="name">
<input type="text" name="age">
<!-- <input type="button" onClick="this.form.action='<?php //echo site_url('core/')?>'+'add_name';this.form.submit();" value="new"/> -->
<input type="button" id="submitFrm" onClick="this.form.submit();" value="new" />
</form>

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>

codeigniter not recognizing some validation

So I have simple registration form and for some weird reason, some of the validation works and some doesn't. I defined a separate language folder for the language in conern i.e. arabic. it works for username, password and password confirmation, but not rest of the fields. What is going wrong?
public function registration()
{
$this->form_validation->set_rules('fullname', 'الاسم الكامل', 'isset | required | alpha');
$this->form_validation->set_rules('username', 'اسم المستخدم', 'required');
$this->form_validation->set_rules('password', 'كلمة السر', 'required');
$this->form_validation->set_rules('passconf', 'إعادة كلمة السر', 'required');
$this->form_validation->set_rules('email', 'الايميل', 'required |email');
$this->form_validation->set_rules('city', 'المدينة', 'required');
$this->form_validation->set_rules('userfile', 'صورة الملف الشخصي', 'upload_no_file_selected');
if($this->form_validation->run() == FALSE)
{
$this->index();
}
else{
$this->user_model->add_user();
$this->thank();
}
}
form:
<html>
<head>
<title></title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
</head>
<body dir="rtl">
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('membership/registration'); ?>
<h5>الإسم الكامل</h5>
<input type="text" name="fullname" value="" size="80" />
<h5>اسم المستخدم</h5>
<input type="text" name="username" value="" size="50" />
<h5>كلمة السر</h5>
<input type="text" name="password" value="" size="50" />
<h5>إعادة كلمة السر</h5>
<input type="text" name="passconf" value="" size="50" />
<h5>الايميل</h5>
<input type="text" name="email" value="" size="50" />
<h5>المدينة</h5>
<select name="city">
<option value="riyadh">الرياض</option>
<option value="jeddah">جدة</option>
<option value="dhahran">الظهران</option>
<option value="mecca">مكة</option>
</select>
<h5>صورة الملف الشخصي</h5>
<input type="file" name="userfile" size="20" />
<br><br>
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Appreciate the help,
Remove the spaces between the validation rules like this:
$this->form_validation->set_rules('fullname', 'الاسم الكامل', 'isset|required|alpha');
I found out the answer and oh is it silly! Just delete the spaces between the validation rules and it all works! so e.g.
alpha|isset|required

Resources