How to reuse form in codeigniter for update and add - codeigniter

Hello i want to reuse a form in codeigniter but problem is the update form is populated one the page has load. Here is a sample form.
<?php
$attributes = array('class' => 'form-horizontal', 'id' => 'addPersonnel');
echo form_open($form_submission, $attributes);
?>
<input type="text" name="name" value="<?php echo set_value('name')?"> >
<input type="text" name="rank" value="<?php echo set_value('rank')?"> >
<button type="submit" class="btn btn-primary">Save</button>
<?php echo form_close()?>
My problem here lies in the set_value() method of the form_validation class since it will have conflict with populating the form if updating.

In your controller update function add a condition like:
if ($this->input->server('REQUEST_METHOD') === 'POST') {
$this->_get_userinfo_form_fields();
} else {
$this->_get_userinfo_form_fields($user_data); //$user_data from database
}
For add function you can directly call - $this->_get_userinfo_form_fields();
Then declare a function as below:
protected function _get_userinfo_form_fields($user_data = array()) {
$this->data['rank'] = array(
'placeholder' => 'Rank',
'name' => 'rank',
'id' => 'rank',
'class' => '',
'value' => isset($user_data['rank']) ? $user_data['rank'] :set_value('rank',$this->input->post('rank',TRUE)),
'style' => '',
);
//Add rest of the fields here like the above one
}
In view file add code like:
<?php echo form_input($rank);?>

Related

Yii2 how to pass variable from view and send to another source

all
My point is.
I need to create a custom report by passing a value from $valiable in view -> controller
my question is how to pass value from $valiable
now I can get value from another system by fix value in $valiable in controller.php
but I need to pass $valiable from view.php that selected after submit button.
something like this
here my code
index.php
<?php $form = ActiveForm::begin(); ?>
<div class="col-xs-12 col-sm-6 col-md-3">
<label class="control-label"> field1 </label>
<?php echo Select2::widget([
'name' => 'field1',
'data' => Report::itemAlias('field1'),
'options' => [
'placeholder' => 'Select Cost Center...',
],
'pluginOptions' => ['allowClear' => true,],
]); ?>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label class="control-label"> field2 </label>
<?php echo Select2::widget([
'name' => 'field2',
'data' => Report::itemAlias('field2'),
'options' => [
'placeholder' => 'Select Fund Center...',
],
'pluginOptions' => ['allowClear' => true,],
]); ?>
</div>
<div class="form-group" >
<?= Html::submitButton('process', ['class' => 'btn btn-warning ']) ?>
</div>
<?php ActiveForm::end(); ?>
in ReportController.php
public function actionIndex ()
{
$array = []; // for array result
$field1 = ''; // if fix value $field1 = 'a'; can pass a to $result
$field2 = ''; // if fix value $field2 = 'b'; can pass b to $result
if (Yii::$app->request->isPost)
{
$FISTL = $_POST['field1']; // view ~field1
$FIPEX = $_POST['field2']; // view ~field2
}
if($field1 !== '' && $field1 !== ''){ *// add if condition for get variable*
$connection = Yii::$app->sconnection->connectionToAnotherSystem(); // connection to another system
$result = $connection->getValue([
'field1' => $field1, // if fix value $field1 = 'a'; can pass a to $result
'field2' => $field2, // if fix value $field2 = 'b'; can pass b to $result
]);
$array = array(['value' =>$result]);//return value from another system
} $dataProvider = new ArrayDataProvider([
'allModels' => $array,
]);
return $this->render('index',
[
'dataProvider' => $dataProvider, // true data
]);
}
EDIT : i got what I want. in controller.php add if condition.
I don't get it at all
But suposing you have the other system's response in $result, it looks like an array; then you are asigning an array in the variable $array that have an assosiative value called 'value'.
The way to get the field1 value is
$array['value']['field1']
You should have a GridView like this in your view php file
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
...
'value.field1',
'value.field2',
...
],
]); ?>
That should works

not able to load validation config file in codeigniter?

I have created an application in CodeIgniter. I'm trying to insert validation in a form. As I will have many forms in my application, so I'm trying to do it with validation config file.
I have created config file in application/config/form_validation.php. I have also autolaoded config file by adding $autoload['config'] = array('form_validation');
Still, my Validation is not working properly it is always returning boolean false
Below code for the same
form_validation.php file
<?php
$config= array(
'Reservation' => array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'required|max_length[50]|min_length[4]|trim|htmlspecialchars|alpha'
),
array(
'field' => 'date',
'label' => 'Date',
'rules' => 'required|trim|htmlspecialchars',
'errors'=> ['required'=>'You must provide a %s for the reservation.']
),
array(
'field' => 'no_people',
'label' => 'No of People',
'rules' => 'required|trim|htmlspecialchars'
)
)
);
?>
index.php - View
<div class="book-reservation wow slideInUp" data-wow-duration="1s" data-wow-delay=".5s">
<?php echo "<script>alert('".validation_errors()."')</script>"; ?>
<?php echo form_open('Entry/Reservation'); ?>
<div class="col-md-12 form-left">
<label><i class="glyphicon glyphicon-calendar"></i>Enter Name:</label>
<input type="text" name='name' value="<?php echo set_value('name'); ?>">
</div>
<div class="col-md-3 form-left">
<label><i class="glyphicon glyphicon-calendar"></i> Date :</label>
<input type="date" name='date' value="<?php echo set_value('date'); ?>">
</div>
<div class="col-md-3 form-left">
<label><i class="glyphicon glyphicon-user"></i> No.of People :</label>
<select class="form-control" name='no_people' value="<?php echo set_value('no_people'); ?>">
<option>1 Person</option>
<option>2 People</option>
<option>3 People</option>
<option>4 People</option>
<option>5 People</option>
<option>More</option>
</select>
</div>
</div>
Entry.php - Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Entry extends CI_Controller {
public function __construct()
{
Parent::__construct();
$this->load->model('Restaurant');
}
public function index()
{
$this->load->view('index');
}
public function Reservation()
{
var_dump($this->form_validation->run('Reservation'));
die;
if($this->form_validation->run() == FALSE)
{
redirect();
}
else
{
#getting values of form
$data['a'] = array(
'Person_Name' => $this->input->post('name'),
'Phone_Number' => $this->input->post('phone'),
'Reservation_Date' => $this->input->post('date'),
'No_People' => $this->input->post('no_people'),
'Reservation_Time' => $this->input->post('time')
);
$data['a'] = $this->security->xss_clean($data['a']); #cleaning data
#calling model
//echo"<pre>";print_r($data['a']);
//die;
if($this->Restaurant->insert_entries($data['a']))
{
$this->session->set_flashdata('message','Your Reservation has accepted, We will call you back shortly.');
redirect();
}
else
{
$this->session->set_flashdata('message','Some techincal issue occured, your reservation did not complete.');
}
}
}
}
Error in below code as it is not redirecting anywhere
if($this->form_validation->run() == FALSE)
{
redirect();
}
Correct Answer:
if($this->form_validation->run() == FALSE)
{
$this->load->view('index');
}

how to retain user input data after validation using codeigniter

I am creating a web app using codeigniter and I am trying to retain user input data on a login form I am using the set value function but the user input is disappearing.
<?php echo form_open('Authentication/login_check',$attributes);?>
<div class="medium-12 columns">
<?php
echo form_label('Email');
$data = array(
'class'=>'form-control',
'name'=>'email',
'id'=> 'email',
'placeholder'=>'Email',
'value' => set_value('email')
);
echo form_input($data);
?>
</div>
<?php echo form_close();?>
You can load form helper in :
application/config/autoload.php
$autoload['helper'] = array('form');
You can set your form look like :
<?php echo form_open('authentication/login_check', '', array('id' => (!empty($attributes)) ? $attributes->id : 0)); ?>
<div class="medium-12 columns">
<?php
echo form_label('Email');
$data = array(
'class'=>'form-control',
'name'=>'email',
'id'=> 'email',
'placeholder'=>'Email',
'value' => set_value('email',($this->input->post('email')) ? $this->input->post('email') : ((!empty($attributes)) ? $attributes->email : ''))
);
echo form_input($data);
?>
</div>
<?php echo form_close();?>

how does one load a div using its id to a view?

how does one load a div using its id to a view?
this is my view
<div id="register" class="animate form">
<section class="login_content">
<form <?php echo form_open('User/register'); ?>
<h1>Create Account</h1>
<div class="inputlogin">
<div class="form-group">
how will i pass it to
if ($this->form_validation->run() === false) {
// validation not ok, send validation errors to the view
$index['title']="Welcome to Hoovie";
$index['mainContent']="login";
$index['results'] = $this->users_model->get_category();
$this->load->view('includes/redirect', $index, $data);
First, form_open tag makes <form> so you can't echo it inside of form it would look like <form <form>>
here is example of login form inside of view:
echo form_open('path/to/controller');
echo form_input(array(
'name' => 'username',
'class' => 'form-control input-lg',
'placeholder' => 'username'
));
echo form_password(array(
'name' => 'password',
'class' => 'form-control input-lg',
'placeholder' => 'password'
));
echo form_submit(array(
'name' => 'LoginSubmit',
'class' => 'btn btn-lg btn-info',
'value' => 'Login'
));
echo form_close();}
After that inside of your controller you have to activate form_validation library if it is not auto-loaded and then you have to set rules for your inputs
example :
$dugme = $this->input->post('LoginSubmit');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if(isset($dugme) && $this->form_validation->run()){
//if everything ok, do something
}
else {
//if validation did not pass load view
$this->load_view('login'); }
and after that inside of view you have to echo errors
//I am using bootstrap so alert-danger will show this div with red background
<?php echo validation_errors('<div class="alert alert-danger">','</div>');?>
you can check more about form validation here :
Codeigniter 3: https://www.codeigniter.com/userguide3/libraries/form_validation.html
Codeigniter 2: https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

Form inputs cannot bypass the form validation in codeigniter version 3.0.0

I am having trouble bypassing the $this->form_validation->set_rules("blah") even when i'm writing the correct inputs. (Using data exisiting in the databases). What happens is that whatever input i do, the form_validation->run() seems to always return false. Please Help Me :(
The View Part (The Form that i'm using):
<div class="navbar-form navbar-right">
<?php
$user = array('name' => 'username', 'class' => 'form-control', 'placeholder' => 'Username', 'autocomplete' => 'off');
$pass = array('name' => 'password', 'class' => 'form-control', 'placeholder' => 'Password', 'autocomplete' => 'off');
$button = array('id' => 'loginbutton', 'class' => 'form-control');
echo form_open('bigphloginc/validateUser');
?>
<div class="form-group">
<?php echo form_input($user); ?>
</div>
<div class="form-group">
<?php echo form_password($pass); ?>
</div>
<div class="form-group">
<?php
echo form_submit($button,'Login');
echo form_close();
?>
</div>
</div>
The Controller i'm Using:
public function validateUser(){
//Gets the posted values
$tempUsername = $this->input->post('username');
$tempPassword = $this->input->post('password');
//Set the rules for forms
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|md5');
if($this->form_validation->run()==FALSE){ //If the form data isn't accepted, loads back to login
redirect(bigphloginc/index);
}else{ //If form data is accepted, checks the database
if(isset($this->session->userdata($tempUsername))){
redirect(bigphloginc/index);
}else{
$this->load->model('bigphuser');
$query = $this->bigphuser->login($tempUsername,$tempPassword);
if($query==FALSE){ //If the form data doesn't exist in db, loads back to login
$this->load->view('warning');
$this->load->view('ilogin');
}else{ //If the form data exist on db, then continues to their respective pages
$data = array(
'username' => $tempUsername,
'password' => $tempPassword,
'type' => $query[0]->type,
'employeeNumber' => $query[0]->employeeNumber,
'loggedIn' => true
);
$this->session->set_userdata($data); //Sets the data to the session
if($query[0]->type=="admin"){ //if the user is an admin
redirect('bigphadmin/home');
}else if($query[0]->type=="employee"){
redirect('bigphemployee/home'); //if the user is an employee
}//Query Type
}//Query false
}
}//validation false
}
xss_clean is no longer part of form validation in codeigniter 3. The alternative is not to use it, as xss_clean is doing sanitization and not validation.
xss_clean is part of security helper.You can use it as
$this->load->helper('security');
$value = $this->input->post('formvalue', TRUE); //TRUE enables the xss filtering
Check this link for more detail

Resources