CodeIgniter's set_value() not re-populating - php

I've checked and re-checked my code, referencing the CI docs and other posts throughout the web, but I am unsuccessful at implementing the set_value() method for re-populating form fields after failed validation.
Perhaps I am missing something very fundamental to the CI framework (I'm rather new to it), but your insight would be much appreciated.
I have the following in my controller method:
public function form_step2(){
//Form Setup
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data['title'] = $this->base_title;
$data['base_url'] = base_url();
//Validation Settings - must be set per step
$this->form_validation->set_rules('request_type', 'Request Type', 'required');
*...more of the same set_rules()*
if ($this->form_validation->run() === FALSE) {
### Validation failed or New Form
// Get form element data
$data['request_types'] = $this->my_model->get_form_data('request_type');
*...more of the same get_form_data() calls for loading form elements*
//Generate Page from View Templates
$this->load->view('templates/header', $data);
$this->load->view('templates/form_step2', $data);
$this->load->view('templates/footer');
} else {
### Save to database
$this->my_model->set_data($data);
redirect('my_model/success','refresh');
}
}
And in my view, a snippet of the code that is not re-populating:
<?php echo form_open('my_model/form_step2', array('class'=>'form-inline')); ?>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" value="<?php echo set_value('fname'); ?>" />
<input type="submit" name="submit" value="Submit" />
I can't figure this one out, so thanks in advance for your help.

if you want to use set_data() you need to also use set_rules for that POST/GET field.
Since you've commented out all your set_rules I can not confirm that this is the issue but most likely it is.
please check if you have this line in your code
$this->form_validation->set_rules('fname', 'First name', 'trim|required');
So if you want to re-populate field with name="fname" you need to have set_rules() // as line above for it otherwise it won't process therefore set_value('fname') is empty.

you surely have found a solution but, for people like me which were spending too many time for this trouble.
I found a solution:
so instead to code that
<input type="text" id="fname" name="fname" value="<?php echo set_value('fname'); ?>" />
Try this, it run very well:
<?php $data = array('id' =>fnam, 'name'=> 'fname','value'=> set_value('fname'), 'size =>'50');
echo form_input($data).'<br />'; ?>

Try this way. It will get both validation errors and set value
In View
<?php echo flash_message();
if($this->session->userdata('postinput') !=""){
$value = $this->session->userdata('postinput');
$this->session->unset_userdata('postinput');
}else
$value = "";
?>
<form action="<?php echo site_url('carlisting/carlist');?>" method="post" id="your_reg_form">
<div class="reg-search">
<input placeholder="YOUR REG" name="input" type="text" value="<?php echo $value; ?>">
</div>
In Controller
$this->form_validation->set_rules('input', 'Registration', 'required|min_length[2]|max_length[7]');
if ($this->form_validation->run() == false){
$this->session->set_flashdata( 'message', array('content' => validation_errors(), 'type' => 'error_message_small' ));
$this->session->set_userdata('postinput',$this->input->post('input'));
redirect('home');
}

Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form. Example:
<input type="text" name="quantity" value="<?php echo set_value('quantity', '0'); ?>" size="50" />
The above form will show "0" when loaded for the first time.

Related

codeigniter post html textarea

when i try to post html from my textarea the variable value is empty and form_validation show error message that the input is required......
i search for solution and i didn't found ....
this is my code
<form accept-charset="utf-8" method="post" action="<?php echo base_url('send_message/validate'); ?>">
<?php
echo validation_errors();
echo form_dropdown('cat_name', $plan_cat);
?>
<div>
<span><label>اسم الراسل باللغه الانجليزية</label></span>
<span><input name="from" type="text" class="textbox" value="<?php echo set_value('from'); ?>" /></span>
</div>
<div>
<span><label>العنوان</label></span>
<span><input name="subject" type="text" class="textbox" value="<?php echo set_value('subject'); ?>" /></span>
</div>
<div>
<span><label>الرساله</label></span>
<?php
/*
$options = array(
'name' => 'message',
'id' => 'elm1'
);
echo form_textarea($options);
*/
?>
<textarea name="message" id="elm1"><?php echo set_value('message'); ?></textarea>
</div>
<div>
<span><input type="submit" value="ارسل" /></span>
</div>
<?php
echo form_close();
?>
and this is my controller code :
$this->load->library('form_validation');
$this->form_validation->set_rules('from', 'الراسل', 'required|min_length[8]');
$this->form_validation->set_rules('subject', 'عنوان الرساله', 'required|min_length[6]');
$this->form_validation->set_rules('message', 'الرساله', 'trim|required|min_length[10]|xss_clean');
if($this->form_validation->run() == false){
$user_id = $this->session->userdata('user_id');
$send = array(
'title' => 'ارسل الرساله',
'plan' => $this->user_plan->get_plan($user_id)
);
$this->load->library('parser');
$this->parser->parse('header', $send);
$this->parser->parse('send_message', $send);
$this->parser->parse('footer', $send);
}else{
$user_id = $this->session->userdata('user_id');
$plan_cat = $this->input->post('cat_name');
$from = $this->input->post('from', true);
$subject = $this->input->post('subject', true);
$message = $this->input->post('message', true);
$message = '<code>'.$message.'</code>';
i hope to find way to solve this :)
First , before going deep in your code , I have to say that : using base_url functionality as action attribute is bad. You have to use site_url instead in this way :
echo site_url('send_message/validate');
The reason stands behind that :
site_url gives you the full URL including the main processing file (index.php) which is important to handle your MVC requests (e.g http://domain.com/codeigniter/index.php/send_message/validate)
base_ur gives you the URL without any consideration for the main file (index.php) (e.g http://domain.com/codeigniter/send_message/validate)
Second (And the important). I see that you are using XSS Filter for the (message) which means you are trying to put illegal content in the textarea. Try to put anything else everything will be ok.
So , make sure that your message value doesn't contain illegal characters.

Prevent form to display default values when validation fails codeigniter

public function edit_profile(){
$logged_in_user = $this->session->userdata('logged_in');
$data['images_url'] = $this->config->item('images_url');
$data['cdn_url'] = $this->config->item('cdn_url');
$data['reminder'] = $this->config->item('reminder');
$data['current_module'] = "ess";
$data['user_details'] = $this->ess->get_user_details($logged_in_user['user_id']);
$this->load->view("header", $data);
$this->load->view("leftbar", $data);
$this->load->view("ess/ess_edit_profile");
$this->load->view("footer", $data);
if($this->input->post('submit')){
$post_data = $this->input->post();
$this->form_validation->set_rules('full_name','Full Name','required|trim|xss_clean');
$this->form_validation->set_rules('email','Email','required|trim|valid_email');
$this->form_validation->set_rules('blood_group','Blood Group','max_length[2]');
$this->form_validation->set_rules('phone','Phone','required|trim|xss_clean');
$this->form_validation->set_rules('address','Address','required|xss_clean|max_length[100]');
$this->form_validation->set_rules('designation','Designation','required|xss_clean');
$this->form_validation->set_rules('emergency_name','Emergency Name','required|xss_clean');
$this->form_validation->set_rules('emergency_number','Emergency Number','required|xss_clean');
$this->form_validation->set_rules('next_of_kin','Next of Kin','trim|xss_clean');
if($this->form_validation->run() === true){
// update data
} else {
$this->load->view("ess/ess_edit_profile");
}
}
}
Above is the function of my controller that loads a edit profile view with database populated values in input fields. Now when the form get submitted after doing editing it goes to validation process in edit_profile() function. I am deliberately running false the validation function for checking purpose. Now if the validation runs === false i loaded the ess_edit_profile view again but the validation messages are not appearing. Also the form fields are getting populated with default values which i've set via set_value() function
Below is how i am showing form fields with database data
<td>
<label for="full_name">Full Name</label>
<input style="width: 300px;" type="text" name="full_name" id="full_name" value="<?php echo set_value('full_name',$user_details[0]->ui_full_name); ?>" />
<?php echo form_error('full_name', '<span class="alert">', '</span>'); ?>
</td>
try this remove else part then try
if($this->form_validation->run() === true){
// update data
}
$this->load->view("ess/ess_edit_profile");
Please use set_value function to set element values
Like this
<input type="text" name="name" value="<?php echo set_value("name", $database_name)?>"/>
In Controller
$this->form_validation->set_rules('name','Edit name','trim|xss_clean|required');
If the value not required then also set validation rules trim
$this->form_validation->set_rules('name','Edit name','trim');

How do you correctly pass post variables from the view to the controller in CodeIgniter?

I haven't used CodeIgniter in nearly a year and I seem to have forgotten a lot of the fundamentals.
I am trying to retrieve the post variables from a form and pass them into a model which inserts them into mysql.
The controller function my form submits to looks like this:
public function validation() {
$this->load->helper("form");
$this->load->model("contact_form");
$data = array(
"name" => $this->input->post("name"),
... etc. etc. ....
);
if ($this->contact_form->new_form($data)) {
$this->load->view("header");
$this->load->view("submitted");
} else echo "Sorry, there was a problem adding the form to the database.";
}
The form in the view is structured like so:
<? echo form_open("form/validation");?>
<div id="one" style="display: block;">
<h1>A Heading</h1>
<p>Some Text</p>
<p class="bold">Name: <input type="text" name="name" class="single" value="<?php echo set_value('name'); ?>"></p>
<p class="bold">Email: <input type="text" name="email" class="single" value="<?php echo set_value('email'); ?>"></p>
<p class="bold">And then some radio buttons</p>
<p> yes <input type="radio" name="registered" value="yes"> no <input type="radio" name="registered" value="no"></p>
<p class="bold">And a textarea...</p>
<textarea name="description" class="fill" value="<?php echo set_value('description'); ?>"></textarea>
next
</div>
<div id="two" style="display:none;">
<h1>Another Heading...</h1>
<p class="bold">And some more textareas</p>
<textarea name="audience" class="fill"></textarea>
... There are four divs in total with further textarea fields ...
<p class="bold"><input type="submit" name="submit" value="submit" class="center"></p>
back
</div>
<? echo form_close();?>
And finally my model is very simple:
class contact_form extends CI_Model {
public function new_form($data) {
$query = $this->db->insert("contact", $data);
if ($query) {
return true;
} else return false;
}
}
The form processes without any errors, but the data just appears as 0's in MySQL. If at any point I attempt to output the value of $_POST it returns BOOL (false), or with $this->input->post('something'); it returns NULL.
You will notice that no actual validation takes place. Initially I was using $this->form_validation->run() and getting the same results. I thought perhaps I was having trouble with the validation so I stripped it out and now I'm fairly certain my problem is that I'm not passing the $_POST variables correctly.
Can anyone explain why I am failing so hard?
I have now resolved this problem.
For some reason <? echo form_open("form/validation");?> was implementing GET and not POST. Replacing that line with <form method="post" accept-charset="utf-8" action="form/validation"/> resolved the issue.
According to the CodeIgniter documentation, by default, form_open should use POST - I have no idea why in my case it decided to use GET.

Codeigniter Form Validation errors with Wrapper

I have built a Login form under PHP Codeigniter framework and its validation rules are set.
The rules are working fine, but what I want to achieve is something different.
The login form has Username & Password Textbox set under a container called control-group.
Those who uses Bootstrap framework for HTML, knows this very well.
So the textbox code is like this :
<div class="control-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="" placeholder="Username" class="login username-field" />
<?php echo form_error('username','<span class="help-inline error">', '</span>'); ?>
</div>
You can see I have also placed span wrappers to error, so that it can be displayed in red color style. But what other thing I want to do is, I want to apply the error class to the control-group.
So that it become from
<div class="control-group">
To
<div class="control-group error">
I have already tried this by taking $error_class variable and passing it from Controller like this.
$data['error_class'] = '';
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE){
$data['error_class'] = 'error';
$this->load->view('administrator/login_view', $data);
}
But what it does is, it applied the error class to the control-group all the time. Even without submitting the form.
Any idea how to achieve this ?
Thanks in advance.
You have to run the validation only when the user is submitting the form.
try doing this
if($this->input->post())
{
//your form validation
}
This will only run when user submits a post request.
EDIT:
In addition to populate error on each individual field, use form_error('field_name') to check for error in each individual fields and echo the error class
eg.
<?=(form_error('field_name')?'error':'')?>

PHP Codeigniter form submit using JQuery

I am new to PHP Codeigniter framework. I am designing a page in which I am using a link. On clicking the link it is calling a jquery function, which submits form through jquery. I have used codeigniter form validation methods for server side validation and for the timebeing I have disabled the client side validation.
The problem is that in this process when the form is submitted through jquery, the codeigniter form validation method is not working.
But if I am using a submit button to submit the form then the codeigniter form validation method works perfectly.
Please advise me what to do if I need to submit the form through jquery and use the codeigniter form validation method.
Please find the code below:
Login Form:
<?php echo validation_errors(); ?>
<form name="login-form" id="login-form" method="post" action="<?php echo base_url();?>index.php/login/login_form" >
<H2>Login</H2>
<div id="login-box-name">
Email:
</div>
<div id="login-box-field">
<input name="user-name" id="user-name" class="form-login" title="Please Enter Correct User Name" value="" size="30" maxlength="2048" />
</div>
<div id="login-box-name">
Password:
</div>
<div id="login-box-field">
<input name="password" id="password" type="password" class="form-login" title="Please Enter Correct Password" value="" size="30" maxlength="2048" />
</div>
<br />
<span class="login-box-options">
<input type="checkbox" name="1" value="1" title="Want this computer to remember you!!"> Remember Me Forgot password?
</span>
<br />
<br />
<a href="" id="login-submit">
<img src="<?php echo base_url();?>assets/images/login-btn.png" width="110" height="40" style="margin-left:90px;" />
</a>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
jquery function to submit the form on clicking the "link":
$("#login-submit").click(function()
{
$('#login-form').submit();
return false;
});
Controller function:
public function login_form()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$data['title'] = 'Log In';
$data['errorMessage'] = '';
$this->form_validation->set_rules('user-name', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('login', $data);
$this->load->view('templates/footer');
}
else
{
$this->load->view('templates/header', $data);
$this->load->view('templates/menu');
$this->load->view('index', $data);
$this->load->view('templates/footer');
}
}
Here if I click on the "Submit button of the form, then the codeigniter validation works for user-name and password fields. But if I click the link with id="login-submit", then it calls the jquery function and the form get submitted. But the codeigniter validation does not work for user-name and password fields this time.
I need to submit the form through the link and the codeigniter validation function should work for this.
Thanks in Advance.....
Use .preventDefault() instead of just returning false on the anchor click event.
This has happened to me before and it seems to me that there is a conflict somewhere using .submit() inside a click event and returning false to stop the anchor's default behavior.
The code above is working fine. Actually I made a silly mistake in my code.
I used following code for jQuery and it is working now.
$("#login-submit").click(function(e) {
e.preventDefault();
$('#login-form').submit();
});
Thanks
it happens because it calls the function all the time when clicking on the button. you need to stop that.
$("#login-submit").click(function(e){
e.preventDefault();
$('#login-form').submit();
});

Categories