I have the following method in my controller:
(shortened version but all the key pieces are here...)
class Widget extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('widget_model');
$this->load->helper('form');
$this->load->library('form_validation');
}
public function assign()
{
//logic to display form.
if ($this->input->method() == "get" ) {
$data['save_status'] = '';
$data['title'] = 'Assign Widget';
$data['main_content'] = "assign";
$this->load->view('includes/template',$data);
}
else
{
//logic to handle POST
...
$data['save_status'] = 'Sucessfully saved to db';
$data['title'] = 'Assign Widget';
$data['main_content'] = "assign";
$this->load->view('includes/template',$data);
}
}
Everything works, except I don't know what the proper way to clear the form data is... because when I press F5 thinking I'm refreshing my page, it's actually resubmitting the data to the database.
Sorry, i'm sure this is a noob question.
Thanks.
EDIT 1
for now, I added a redirect at the end of post logic like this;
redirect(base_url()."index.php/thesamecontroller/thesamemethod");
and that takes the user to the same page, but without the form data being available.
Is this the best way to handle it?
Related
I am new to developing, and I want to do a simple validation in Codeigniter. I don't know where I am going wrong.
This is my form to be validated
And my controller is this
public function __construct()
{
parent::__construct();
$this->load->model('M_menu');
$this->load->model('master/M_user_type');
$this->load->helper(array('form'));
$this->load->library('form_validation');
}
public function index()
{
$data['menus']=$this->M_menu->getSideBarMenu_m();$data['error_message'] = '';
$this->load->view('master/V_user_type',$data);
}
function saveUserType_c()
{
$data['error_message'] = '';
$this->form_validation->set_rules('userType', 'UserTypeName', 'required');
echo var_dump($this->form_validation->run());
if (!$this->form_validation->run() )
{$data['menus']=$this->M_menu->getSideBarMenu_m();
$data['error_message'] .= validation_errors();
$this->load->view('master/V_user_type',$data);
}
else
{
$insert=$this->M_user_type->saveUserType_m();
if($insert){
$response=array("insert"=>true);
}else{
$response=array("insert"=>false);
}
echo json_encode($response);
}
}
With this I get the network error, and data is being saved to db. But no action in form(form not loading). Please guide me, where I go wrong. Also, if I need to give any more details
Please check your usertype view page, you can also load usertype view page before validation, so that you will be confirmed that usertype view page exist, I hope you understand my point.
You have to load a model before you call its methods. Use this:
$this->load->model('M_user_type');
$insert=$this->M_user_type->saveUserType_m();
I have this admin panel where I use different data-toggle tabs.
In CI(3), if I go with redirect('user/dashboard#new'); , it redirects me to correct section of view but not with form_validation errors.
And if I try $this->dashboard('user/dashboard#new'); it renders the errors but leads me to the wrong section of page (not at #new).
I have just started developing with CI and looking for some help from seniors.
Thanks in advance.
Controller (user)
public function dashboard() {
if($this->session->userdata('is_logged_in')){
$data['homepage'] = '../../templates/vacations/users/dashboard';
$this->load->view('template_users',$data);
}else{
$data['session_error']='Either the session has expired or you have tried to access this page directly';
$this->load->view('../../templates/vacations/headfoot/header-login');
$this->load->view('../../templates/vacations/users/session-error', $data);
$this->load->view('../../templates/vacations/headfoot/footer-login');
}}
Form Validation
if($this->form_validation->run() == FALSE)
{
$this->dashboard('user/dashboard#new');
} else {
$this->load->model('model_users');
if($query = $this->model_users->insert_property_details())
{
redirect('user/dashboard#new');
} else {
redirect('user/dashboard#new');
}}}
$this->dashboard('user/dashboard#new'); just runs/calls the method within the current page. 'user/dashboard#new' does nothing because the method is not written to accept arguments anyway:
public function dashboard(/* arguments would be here normally */) { ... }
Redirecting right after running validation won't work because you will lose the validation errors when you load a new page.
You need to save the errors somewhere, such as to session data, then redirect to dashboard, and then load the errors from saved location and display them on the dashboard view.
Here's an example using session data.
Form method:
if($this->form_validation->run() == FALSE)
{
$this->session->set_userdata('validation_errors', validation_errors());
$this->session->mark_as_flash('validation_errors'); // data will automatically delete themselves after redirect
redirect('user/dashboard#new');
}
else { ... }
Dashboard method:
public function dashboard()
{
if($this->session->userdata('is_logged_in')){
$data['validation_errors'] = $this->session->userdata('validation_errors');
$data['homepage'] = '../../templates/vacations/users/dashboard';
$this->load->view('template_users',$data);
} else { ... }
}
Getting error array from form validation class (for comments below):
class MY_Form_validation extends CI_Form_validation {
public function error_array()
{
return $this->_error_array;
}
}
When i click on back button, i got the confirm form submission error .How to prevent this issue?Please provide solution for this.
I am trying to login to the admi panel and edit in admin in this following code
Admin controller:
public function index()
{
$data = $this->data;
$this->load->view('admin/login.php',$data);
}
public function login()
{
$data = $this->data;
$username=$this->input->post("username");
$password=$this->input->post("password");
if($username=='admin'&&$password=='admin123')
{
$this->load->view('admin/home.php',$data);
}
else
{
$data['error']="Invalid Username or Password";
$this->load->view('admin/login.php',$data);
}
}
/* Function For Displaying the home page*/
public function home()
{
$data = $this->data;
$this->load->view('admin/index.php',$data);
}
/* Common Function for calling the View*/
public function _admin_output($output = null)
{
$output->base=$this->config->item('base_url');
$output->site=$this->config->item('site_url');
$output->css=$this->config->item('css');
$output->js=$this->config->item('js');
$this->load->view('admin/home_page.php',$output,'refresh');
}
public function loadSlidingimg()
{
$crud = new grocery_CRUD();
$crud->set_table('tbl_slideimg');
$crud->columns('imgname','active');
$crud->set_subject('Frontpage Sliding Images');
$crud->display_as('imgname','Image name');
$crud->set_field_upload('imgname','uploads');
$crud->display_as('active','Active Flag');
$crud->callback_after_update(array($this,'rename_slideimg_db'));
$crud->callback_after_insert(array($this,'rename_slideimg_db'));
$output = $crud->render();
$this->_admin_output($output);
}
}
Please provide solution for this issue
It happens because the action that took you to that page was a POST request. The browser wants to save you from unintentional double-ordering/paying/whatever when you go "back", when loading that page would need to do the form posted again.
How to work that around? I usually redirect the user to a page which was loaded by a GET request, it can be even the same page, see this answer: https://stackoverflow.com/a/3968038/357403
Or, you could modify the history: https://developer.mozilla.org/en-US/docs/Web/API/History_API
Also, please see the PRG pattern: https://en.wikipedia.org/wiki/Post/Redirect/Get
Try this code format:
$this->load->view('admin/home.php', 'refresh', $data);
or
redirect('home', 'refresh');
I am facing a problem with the submit form, I have a view that shows data from database with and edit button beside each record that pops up div with a form to update that specific record. The problem is that when I submit the form and the data is saved in the database, the view would show the the record with the old data, unless I hit the refresh button in the browser. (the codeigniter cache is set to FALSE)
the controller:
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Product extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('Table');
$this->load->library('DX_Auth');
// $this->load->library('pagination');
$this->load->helper('form');
$this->load->helper('url');
// Protect entire controller so only admin,
// and users that have granted role in permissions table can access it.
$this->dx_auth->check_uri_permissions();
$this->load->model('Product_model');
$this->load->library('Form_validation');
}
function index($sort = 0, $offset = 0) {
$data['product'] = $this->Product_model->get_all()->result_array();
if (isset($_POST['save'])) {
$this->form_validation->set_rules('link', 'Link', 'trim|required|xss_clean|prep_url');
$this->form_validation->set_rules('video', 'Video', 'trim|required|xss_clean|prep_url');
if ($this->form_validation->run() === TRUE) {
$post = $this->input->post();
if(!isset($post['link_target_blank'])){
$post['link_target_blank'] = 0;
}
unset($post['save']);
unset($post['id']);
$this->Product_model->update_settings($this->input->post('id'), $post);
}
}
// Load view
$header_data['title'] = 'Game Product';
$this->load->view($this->config->item('header_view'), $header_data);
$this->load->view($this->config->item('blocks_view') . 'head_block');
$this->load->view($this->config->item('menus_view') . 'main_menu');
$this->load->view('backend/product', $data);
$this->load->view($this->config->item('footer_view'));
}
}
?>
Because your get request:
$this->Product_model->get_all()->result_array();
Is before your insert/update request:
$this->Product_model->update_settings($this->input->post('id'), $post);
Therefore when you get all, the data isn't there yet.
If you put the get after your if statement - then it should work, e.g:
if (isset($_POST['save']))
{
// all your POST processing and saving...
}
$data['product'] = $this->Product_model->get_all()->result_array();
I'm building a small application that will basically display 3 forms... the first one is optional, the second not and the third not. I'd like each form to be a separate url(controller). While reading the documentation for the CodeIgniter form_validation, it appears that the form can only submit to it's self to validate. If that's the case, the forms would keep showing on the same page... he's basically what I have... and commented in what i'd like to do...
class Index extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
//load front page that contains first form...
$content['title'] = 'Home';
$content['view'] = 'pages/index';
$this->load->view('template/default',$content);
}
function step_two()
{
//recieve information from front page. validate form. If validation is
//successful continue to step_two(url) if it fails redirect
//to front page with error...
$this->form_validation->set_rules('serial', 'Serial Number', 'required');
if ($this->form_validation->run() == FALSE)
{
//return to front page...
}else{
//do necessary work and load step_two view
}
}
}
?>
This is a snippet from my idea. But what I'm noticing is that you can't have form validation unless the form submits to it's self. Any ideas? Should I validate the form then just redirect to the new url/function?
Thanks guys...
this is how you do it
Controller -
public function step1()
{
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform1');
}
else
{
//do something to post data
redirect('/controller/step2');
}
}
public function step2()
{
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform2');
}
else
{
//do something to post data
redirect('/controller/step3');
}
}
so answer to your question is yes, you keep these in the same method and redirect on successful validation.