CodeIgniter get values back if validation fails - validation

I am new at codeigniter and I got a question. I have a form with validation and that works fine, but say if I enter data in a field and leave the rest blank, the validation will show me the errors and clear the data that has been entered....how do I fix this?
Here is my controller code:
function submitclub()
{
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('firstname', 'First Name', 'required');
if ($this->form_validation->run() == FALSE)
{
$dataclub['clubname'] = $this->club_model->get(0, FALSE);
$dataclub['division'] = $this->division_model->get(0, FALSE);
$data['reset'] = TRUE;
$view = 'individual/individual_view';
}
Any help would be much apperciated

Solved this by doing this in my view:
<?php echo form_input('lastname', set_value('lastname'), 'id=lastname'); ?>
<?php echo form_error('lastname'); ?>

Related

Sweet Alert2 not showing up after form validation in CI

Hello i'm trying to show up the alert after validation succes ,but the alert not showing up .
code wrong or what ??
public function dashboard()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]');
$this->form_validation->set_rules('pass', 'Password', 'trim|required|min_length[5]');
if($this->form_validation->run() != false){
echo "<script>
Swal.fire('Login Success')
</script>";
}else{
$this->load->view('login');
}
}
Are there any errors logged? I usually close php with then execute the Javascript then open it again.
public function dashboard()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]');
$this->form_validation->set_rules('pass', 'Password', 'trim|required|min_length[5]');
if($this->form_validation->run() != false){
?>
<script>
Swal.fire('Login Success');
</script>
<?php
}else{
$this->load->view('login');
}
}

Yii2 dropDownList get selected value

I have dropDownList in my view ( data from db) :
use yii\widgets\ActiveForm;
\app\assets\HelloAsset::register($this);
$form = ActiveForm::begin();
$users=\app\models\User::find()->all();
$items=\yii\helpers\ArrayHelper::map($users,'id','username');
echo $form->field($model, 'username')->dropDownList($items);
echo \yii\bootstrap\Html::submitButton('Send');
ActiveForm::end();
I want to get data from 'username' in my controller:
$model=new Data();
if ($model->load(\Yii::$app->request->post())){
echo 'it is status:'.$model->username;
}else {
return $this->render('simple', ['model' => $model]);
}
But data is null.
How I must get data in right?
Please, help me solve this problem.

Dependanat Drop down is not working when it has only one value in yii framework

I am using dependant dropdownlist for get value for subject dropdown when select value from 'Grade' dropdown. It is working fine. But the problem is when there are only one value in grade dropdown the subject dropdown is not updated.
this is my code:-
Grade DropDown----------
($data is consist of grade)
<?php echo CHtml::dropDownList('myDropDown1','',$data,array(
'id'=>'gr',
'empty' => '(Select Grade)',
'style'=>'width:200px',
'ajax' =>
array(
'type'=>'POST', //request type
'url'=>CController::createUrl('sub'), //action to call
'update'=>'#cls', // which HTML element to update
)
)); ?>
Subject Dropdown (which depend on grade dropdown)------------
<?php echo CHtml::label('Subject',''); ?>
<?php echo CHtml::dropDownList('myDropDown3','',array(),array(
'id'=>'sub',
'prompt'=> 'Please select a class', 'style'=>'width:150px',
'style'=>'width:200px',
)); ?>
<?php //echo $form->error($model,'sub_id'); ?>
In controller-------------------
public function actionClass()
{
$grd = $_POST['myDropDown1'];
$c_id = TbClass::model()->findAll('id=:id',
array(':id'=>$grd,));
$data3 = CHtml::listData($c_id,'id','grade');
$grd2 = array_shift($data3);
$sub1 = TbClass::model()->findAll('grade=:grade',
array(
':grade'=>$grd2,
));
$data4 = CHtml::listData($sub1,'id','class');
foreach($data4 as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
This code is working fine. Problem is when grade has only one value in the dropdown , cannot update the subject dropdown.
I think your problem is in array_shift,
have you checked the value of $grd2 ?

How to show validation errors using redirect in codeigniter?

I have been dealing with a problem for a while. How can I set the validation errors using redirect in a function? This is the code I have in my controller :
function send()
{
$this->form_validation->set_rules('e-mail', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('cellphone', 'Cellphone Number', 'trim|required|is_natural');
$this->form_validation->set_message('required', '%s is required.');
$this->form_validation->set_message('valid_email', '%s is not a valid Email Address');
$this->form_validation->set_message('is_natural', '%s can only contain numbers.');
$this->form_validation->set_error_delimiters('<li>', '</li>');
if($this->form_validation->run() == FALSE)
{
redirect ('/');
}
else
{
echo '<pre>';
print_r($_POST);
echo '<pre>';
}
}
And this is the code I use in my view file:
<? if (validation_errors())
{
echo '<div id="validation_errors" title="Error:">';
echo '<div class="response-msgs errors ui-corner-all"><span>Errors:</span><br /><ul>';
echo validation_errors();
echo '</ul></div>';
echo '</div>';
}
?>
I found the way to do it. Redirecting does not keep the data to be shown. I used the code below to solve the problem:
if($this->form_validation->run() == FALSE)
{
$this->index();
}
I know it's a bit late but this method works wonders for me.
If you are validating your form in a different function than the one the form is loaded in, you can send your validation_errors() to any page that you redirect() by passing the validation_errors() method to $this->session->set_flashdata() like so:
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error', validation_errors());
redirect('/');
}
In your controller functions where you would like your errors or messages to be received you can then set them to the $data array like so:
if (!empty($this->session->flashdata('message'))) {
$data['message'] = $this->session->flashdata('message');
} elseif (!empty($this->session->flashdata('error'))) {
$data['error'] = $this->session->flashdata('error');
}
At the top of my views I usually include:
<?php if (isset($message)) {
echo '<p class="alert alert-info">'.$message.'</p>';
} elseif (isset($error)) {
echo '<p class="alert alert-danger"><strong>Error: </strong>'.$error.'</p>';
}?>
Using twitter bootstrap classes to format the messages helps to differentiate them.
I included the message flashdata so that you can see how whatever type of message or error you want to send, you are able to format them differently for all information, warning, success and error messages.
As per my comment:
function index()
{
$this->load->library('form_validation');
$data = array
(
'Param' => 'Value'
);
if($this->input->post('cellphone', true) !== false)
{
if($this->form_validation->run() != FALSE)
{
echo '<pre>' . print_r($_POST, true) . '</pre>';
}
}
$this->load->view('index', $data);
}
First, you need to change your form so it points to the current page, i.e. current_url() or site_url('controller/index').
When you go to the index without posting, it will simply skip the validation. Upon submitting your form, it will run the validation.
You can then use the built in form_error or validation_errors methods to display the errors within your index view.
finally i got a solution for the redirect with validation_errors
This is using to pass the validation_errors in the session data,
i do it like this
if ($this->form_validation->run()) {
$data = array(
'email' => $this->input->post('email'),
'is_login' => true
);
$this->session->set_userdata($data);
redirect($this->input->post('redirect'));
}
else
{
$data = array (
'errors' => validation_errors(),
'is_login' => false
);
$this->session->set_userdata($data);
redirect($this->input->post('redirect'));
}
and in the page i used
$this->session->set_flashdata('redirectToCurrent', current_url());
if ($this->session->userdata('is_login'))
{
echo "You are using this as : </br>" . $this->session->userdata('email');
echo "</br><a href='/logout'>Logout</a>";
}
else
{
echo form_open('login');
echo "" . $this->session->userdata('errors');
echo "email : " . form_input('email');
echo "Password : " . form_password('password');
echo form_submit('submit', 'Login');
echo form_hidden('redirect',$this->uri->uri_string());
echo form_close();
}
I wish you like this fast solution

Issue with active record update in CodeIgniter

I have a form that submits data to a database in a CodeIgniter app (CI v. 2.0.2). We are allowing users to "edit" records by having them resubmit a record with new values and then doing an update. On submit, the form calls the vote controller's create method. Inside the create method, we check to see if there's already a record based on an entry code and the user's ID. If there is, we update; otherwise we create a new record. The creation works just fine; it's only the update I'm having an issue with. Here's the code.
view
<div id="vote_form">
<?php
$hidden = array('dot_judge_id' => $this->session->userdata('dot_judge_id'));
echo form_open('vote/create');
$entry_code_data = array(
'name' => 'entry_code',
'id' => 'entry_code',
'value' => set_value('entry_code')
);
echo form_hidden($hidden);
$score_options = array('1'=>'1 (lowest)', '2'=>'2','3'=>'3', '4'=>'4','5'=>'5 (highest)');
?>
<p><label for="entry_code">Entry code: </label><?php echo form_input($entry_code_data); ?></p>
<p><label for="q1">Question 1: </label><?php echo form_dropdown('q1', $score_options, ''); ?></p>
<p><label for="q2">Question 2: </label><?php echo form_dropdown('q2', $score_options, ''); ?></p>
<p><label for="q3">Question 3: </label><?php echo form_dropdown('q3', $score_options, ''); ?></p>
<p><label for="q4">Question 4: </label><?php echo form_dropdown('q4', $score_options, ''); ?></p>
<p><label for="q5">Question 5: </label><?php echo form_dropdown('q5', $score_options, ''); ?></p>
<p><?php echo form_submit('submit', 'Submit vote'); ?></p>
<?php echo form_close(); ?>
<?php echo validation_errors(); ?>
</div>
controller
function create() {
$id = $this->input->post('entry_code');
$judge_id = $this->input->post('dot_judge_id');
$data = array(
'entry_code' => $id,
'dot_judge_id' => $judge_id,
'q1' => $this->input->post('q1'),
'q2' => $this->input->post('q2'),
'q3' => $this->input->post('q3'),
'q4' => $this->input->post('q4'),
'q5' => $this->input->post('q5'),
);
//first check to see if there's already a record for this judge/entry
//if so, update. Otherwise, insert
$vote_id = $this->vote_model->getEntryById($id, $judge_id);
if($vote_id) {
log_message('debug', 'vote id exists: '.$vote_id);
$this->vote_model->updateRecord($data, $vote_id);
}
else {
log_message('debug', 'vote id does not exist; creating new');
$this->vote_model->createRecord($data);
}
/*
after submission, go to another page that gives choices - review entries, submit another entry, log out
*/
$data['msg'] = "Entry submitted";
$this->menu();
}
model
function getEntryByID($id, $judge_id) {
//determine if record already exists for entry/judge
$sql = 'SELECT vote_id from dot_vote WHERE entry_code = ? AND dot_judge_id = ?';
$query = $this->db->query($sql, array($id, $judge_id));
if($query->num_rows() == 1) {
$row = $query->row();
return $row->vote_id;
}
else {
return false;
}
}
function createRecord($data) {
$this->db->insert('dot_vote', $data);
return;
}
function updateRecord($data, $vote_id) {
log_message('debug', 'vote id is passed: '.$vote_id);
$this->db->where('vote_id', $vote_id);
$this->update('dot_vote', $data);
}
I know it's making it into the updateRecord method because the log_message output is in my log file displaying the correct vote_id (the auto-increment field of the returned record). But what I get in the browser is the following:
Can anyone point me in the right direction here? I have error display on in my config file, and have gotten SQL errors when they occur, so I don't think this is a SQL error. But I have no idea what could be happening in that tiny little function that's causing this. My next step is to skip the active record update and just use a standard query, but I'd like to know what's causing the problem here, even if I can get it to work the other way.
This line stood out:
$this->update('dot_vote', $data);
Do you mean this?
$this->db->update('dot_vote', $data);

Resources