I have a controller which loads the view like this:
class A extends Controller{
public function simpleForm(){
//this generates the form
}
public function simpleFormSubmitted(){
// Simple form is submitted here. Here I perform validation and if
// validation fails I want to display simpleform again with all the values
// inputted by the user as it is and if validation succeeds I want to
// redirect to some other page. I am using simple HTML to generate the
// form and not the formhelper of CodeIgniter because I am more comfortable
// with HTML rather than remembering the syntax of CodeIgniter.
}
}
Here is how to preserve the form fields when dealing with errors...
$fields['username'] = 'Username';
$fields['password'] = 'Password';
$fields['passconf'] = 'Password Confirmation';
$fields['email'] = 'Email Address';
$this->validation->set_fields($fields);
This is how to re-populate the HTML form...
<?php echo $this->validation->error_string; ?>
<?php echo form_open('form'); ?>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo $this->validation->username;?>" size="50" />
For more information look over here - Form Validation in Codeigniter
Look for the heading Re-populating the form
in function simpleForm add default variables so, after validation you can call it again with userform values
class A{
public function simpleForm($val1="", val2="", $val3=""){
//this generates the form
}
public function simpleFormSubmitted(){
//simple form is submitted here. Here is perform validation and if validation fails i
if(!$valid){
$result = $this->simpleForm($val1, $val2, $val3 etc...)
}
else{
$result = //whatever you need to output after validation success
}
return $result
}
}
Related
In my codeigniter controller function call $this->form_validation->run(), that return always false, and my validation_errors() not showing error, probably because not receive datas in post method...
my controller
class Reminder extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('reminder_model');
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->library('email');
$this->load->library('session');
if(!$this->session->auth_ok) {
redirect('auth/login');
}
}
public function index(){
$data['title'] = 'Reminder';
$data['section'] = 'reminder';
$data['reminders'] = $this->reminder_model->getReminders();
$data['operatori'] = $this->reminder_model->getOperators();
$this->form_validation->set_rules('selectUser','selectUser', '');
if($this->form_validation->run() === FALSE) {
$this->load->view('common/header2', $data);
$this->load->view('reminder/index', $data);
$this->load->view('common/footerReminder');
echo validation_errors();
}else{
echo "<pre>";
print_r($this->input->post());
die();
}
}
my view
<?php echo form_open('reminder/index'); ?>
<div class="form-group">
<label for="selectUser" style=" width: 30%">Utente: </label>
<select class="form-control" name="selectUser" id="selectUser" style="width: 30%">
<?php foreach($operatori as $operatore): ?>
<option value="<?php echo $operatore['ID']?>" <?php echo $r = ($operatore['ID']==$this->session->auth_user['ID']) ? 'selected' : '' ?>><?php echo $operatore['nome']." ".$operatore['cognome'] ?></option>
<?php endforeach; ?>
</select>
</div>
<button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> View</button>
<?php echo form_close(); ?>
In order to get the entire $_POST array using CodeIgniters built-in methods, you have to set the first parameter as NULL and the second parameter as TRUE
Like this:
$this->input->post(NULL, TRUE);
Also, you have not set any rules for validation..
In CodeIgniter, you set rules in the third parameter of the set_rules method within the form_validation object.
Like this:
$this->form_validation->set_rules($FIELD_NAME, $FIELD_NAME(for error messages), $RULES);
You would substitute the first $FIELD_NAME with the value of the name attribute on the HTML element you are looking to validate.
You would substitute the second $FIELD_NAME with the name you would like to use for the field when displaying an error message to the user.
You would substitute $RULES with the validation rules such as: 'required|min_length[#]|max_length[#]'
Hope this helps!
If you are not setting rules (which makes it rather pointless to use $this->form_validation->set_rules()) the form validation will fail as it's missing a required parameter.
If you don't need to validate a field, don't set a rule.
Try updating your set_rules instruction to $this->form_validation->set_rules('selectUser','selectUser', 'required'); to see if it behaves correctly. You can verify by filling something in the form (validation will pass) or leaving the field blank (validation will fail)
Just remember, if you won't set at least one validation rule for a field, don't instantiate the set_rules method for that field
I'm learning Codeigniter and I have a controller named Admin controller
class Admin extends CI_Controller{
/* skipped */
//This function is used to generate changepassword form
public function changepassword(){
$this->data['sessiondata'] = $_SESSION['logged_in'];
$this->data['mainview'] = 'components/admin/changepassword';
$this->load->view($this->layout, $this->data);
}
//changepassword form will be submitted to this function ('admin/checkpassword')
public function checkpassword(){
$error = array(
'required' => '%s tidak boleh kosong',
'matches' => '%s tidak sama, dumb ass'
);
/* some validations skipped */
if($this->form_validation->run($this) == FALSE){
$this->data['mainview'] = 'components/admin/changepassword';
$this->load->view($this->layout, $this->data);
} else {
$tobesent = array(
"oldpassword" => $this->input->post('oldpassword'),
"newpassword" => $this->input->post('newpassword'),
"verifynewpasswprd" => $this->input->post('verifynewpassword')
);
$this->admincrud->changepassword($tobesent);
$this->data['result'] = "Password sukses diubah";
$this->data['mainview'] = 'components/admin/changepassword';
$this->load->view($this->layout, $this->data);
}
}
}
the result is, each time I go to base_url('admin/changepassword'), fill the provided form and then submit the form, my url changes from base_url('admin/changepassword') into base_url('admin/checkpassword'), which I know came as the result of submitting the form. Also each time I type base_url('admin/checkpassword') directly on my address bar, it opens the form, which I know came as the result of the if-else condition in checkpassword function. My question is, from the security standpoint, is it okay if I keep using this structure? and how can I prevent users from directly accessing base-url('admin/checkpassword') and instead redirecting them to base_url('admin/changepassword') ?
well if you don't want the URL to be changed after submitting the form.
You can use redirect('admin/changepassword'); and since you need to provide
messages accordingly, you can use $this->session->set_flashdata('msg','Your message'); before redirection and use it in view like this:
<?php if($this->session->flashdata('msg') <> NULL){echo $this->session->flashdata('msg');} ?>
Solution to your problem is $_SERVER['REQUEST_METHOD'] if i understood correctly...
For example :-
if($_SERVER['REQUEST_METHOD'] == 'POST')//form method is post
{
//checkpassword code
}
else
{
redirect(base_url('admin/changepassword'));
}
I need a help..
I have a unique form with multiples fieldsets, and i need separate some fieldsets in tabs..
So, i tried in the view (form is my variable with the whole form):
$form = $this->form;
$customFieldset = $form->get('customFieldset');
$form->remove('customFieldset');
It works, my fieldset form is in $customFieldset.. but, i can't render this!
When a try:
echo $this->form($customFieldset);
//OR
echo $this->formInput($customFieldset);
//OR
$this->formCollection($customFieldset);
None of that works..
I'm doing right? How i can do it?
Thank very much.
To achieve the result you want (using the form across several tabs, it is better to construct the form differently, based on the tab's number. For example, your form constructor method would look like below:
<?php
namespace Application\Form;
use Zend\Form\Form;
// A form model
class YourForm extends Form
{
// Constructor.
public function __construct($tabNum)
{
// Define form name
parent::__construct('contact-form');
// Set POST method for this form
$this->setAttribute('method', 'post');
// Create the form fields here ...
if($tabNum==1) {
// Add fields for the first tab
} else if($tabNum==2) {
// Add fields for the second tab
}
}
}
In the example above, you pass the $tabNum parameter to form model's constructor, and the constructor method creates a different set of fields based on its value.
In your controller's action, you use the form model as below:
<?php
namespace Application\Controller;
use Application\Form\ContactForm;
// ...
class IndexController extends AbstractActionController {
// This action displays the form
public function someAction() {
// Get tab number from POST
$tabNum = $this->params()->fromPost('tab_num', 1);
// Create the form
$form = new YourForm($tabNum);
// Check if user has submitted the form
if($this->getRequest()->isPost()) {
// Fill in the form with POST data
$data = $this->params()->fromPost();
$form->setData($data);
// Validate form
if($form->isValid()) {
// Get filtered and validated data
$data = $form->getData();
// ... Do something with the validated data ...
// If all tabs were shown, redirect the user to Thank You page
if($tabNum==2) {
// Redirect to "Thank You" page
return $this->redirect()->toRoute('application/default',
array('controller'=>'index', 'action'=>'thankYou'));
}
}
}
// Pass form variable to view
return new ViewModel(array(
'form' => $form,
'tabNum' => $tabNum
));
}
}
In your view template, you use the following code:
<form action="">
<hidden name="tab_num" value="<?php echo $this->tabNum++; ?>" />
<!-- add other form fields here -->
</form>
I am creating a search page in my CodeIgniter project.
On submit, the form calls the controller function, data is fetched via model function and the resulting array is passed to the view
The problem is that when I refresh the result page the form is resubmitting because the $_POST data is still there in the request headers.
How can I avoid that resubmit confirmation message
Following is the code for my form :
<!--form-->
<form id="find" action="<?php echo base_url()?>search/find" method="post">
<input type="text" name="search_key" class="tb4" id="search_key" placeholder="Search here"/>
<input type="button" value="search"/>
</form>
Following is the code for my controller:
/*
* function for fetching search results
* #param void
* #return void
*/
public function find()
{
$data['search_result']=$this->search_model->search($this->input->post('search_key'));
$this->load->view('template/header');
$this->load->view('pages/search_result',$data);
$this->load->view('template/footer');
}
Kindly help me with this.I can't use redirect instead of loading the view since I am bound to pass the result array $data to the view.
Try redirect to itself
public function find()
{
$data['search_result']=$this->search_model->search($this->input->post('search_key'));
if($this->input->post('search_key')) {
redirect('yourcontroller/find');
}
$this->load->view('template/header');
$this->load->view('pages/search_result',$data);
$this->load->view('template/footer');
}
Simple solution is to have a hidden timestamp field in the form.
<?php echo form_hidden( 'TS', time() ); ?>
When the form is processed, save this timestamp in the session,
$this->session->set_userdata( 'form_TS', $this->input->post( 'TS' ) );
Before processing the form check that two timestamps doesn't match
if ( $this->input->post( 'TS' ) != $this->session->userdata('form_TS') )
{...}
IF you want to avoid the resubmit then please after save redirect on same controller like this
It can be solved using session. If there is any POST form submit,
ie
if (count($_POST) > 0){
$this->session->set_userdata('post_data', $_POST );
redirect('same_controller');
}
else{
if($this->session->userdata('post_data')){
$_POST = $this->session->userdata('post_data');
$this->session->unset_userdata('post_data');
}
}
Kindly use this:
$post_data = $this->session->userdata('post_data');
if ($post_data == $_POST){
$this->session->unset_userdata('post_data');
redirect(current_url(), 'refresh');
}else{
$this->session->set_userdata('post_data', $_POST );
}
I have a form set up in a controller that both loads the form and its previously populated contents from a database and processes the form as needed. The problem is $this->form_validation->run() never evaluates to FALSE, even if rules are not met.
Controller:
public function edit_version($node, $lang)
{
// load form validation class
$this->load->library('form_validation');
// set validation rules
$this->form_validation->set_rules("title|Title|required");
// run validation
if ($this->form_validation->run() !== FALSE)
{
// save input to database
die("validation successful");
}
else
{
// either validation was not passed or no data to validate
// load page edition view and display databse contents
// load page model
$this->load->model("page_model");
// get the page from database
$data["page"] = $this->page_model->get_page($node, $lang);
// load views
$this->load->view("admin/header.php", array("title" => "Edit page no.: $node, $lang version - Admin"));
$this->load->view("admin/pages/edit_page.php", $data);
$this->load->view("admin/footer.php");
}
}
Model:
class Page_model extends CI_Model
{
public function get_page($node, $lang)
{
// load the page
return $this->db->get_where("pages", array("node" => $node, "lang" => $lang))->row();
}
public function save_version($page)
{
$this->db->where("node", $page["node"]);
$this->db->where("lang", $page["lang"]);
$this->db->update("pages", $page);
}
public function search($query)
{
return $this->db->get_where("pages", $query)->result();
}
}
View:
<h2>Edit page</h2>
<?php
// load form helper
$this->load->helper("form");
// open a form
echo form_open("admin/page/{$page->node}/edit/{$page->lang}");
// print validation errors
echo validation_errors();
// title and content fields
echo form_label("Title: ", "title");
echo form_input("title", set_value("title", $page->title));
// aesthetic line break
echo "<br>";
echo form_label("Content: ", "content") . "<br>";
echo form_textarea("content", set_value("content", $page->content));
// save button and close form
echo form_submit("submit", "Save page");
echo form_close();
Thanks in advance.
syntax for setting rule is
$this->form_validation->set_rules('field_name', 'Label', 'rule1|rule2|rule3');
by considering rules your set rule line will be
$this->form_validation->set_rules('title','Title', 'required");
I'm not a CodeIgniter seasoned dev but from documentation is the proper syntax not the following?
$this->form_validation->set_rules("title","Title","required");
As per this link:
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules
Use
$this->form_validation->set_rules("title","Title","required");
instead of this
$this->form_validation->set_rules('title','Title','required');
I have tested this. It works like a Charm.