Codeigniter - add method URL & Redirect issue - php

I have a method in CI which basically adds a user to a table - if any form validation occurs it reloads the view - if successful it reloads the view to show that the user was added successfully. As seen below:
public function loadPeopleView(){
//loads unit page view
$this->load->model('people_model');
$people['people'] = $this->people_model->getPeople();
$this->load->view("header");
$this->load->view("people page/people_view", $people);
$this->load->view("footer");
}
public function addPerson(){
$this->form_validation->set_rules('personName', 'personName', 'required|min_length[6]|max_length[150]|trim|xss_clean');
$this->form_validation->set_rules('personPet', 'personPet', 'required|trim|min_length[3]|max_length[30]|xss_clean');
if($this->form_validation->run()){
$this->load->model('');
$this->people_model->addPerson();
$this->loadPeopleView();
} else{
//if validation fails - returns the peopl view this display error messages
$this->loadPeopleView();
}
}
my issue is when someone adds a person the browser remains on:
localhost/peoplecontroller/addperson
if the user keeps refreshing the page - loads of people will continue to be added in - is there anyway I can put the page back to:
localhost/peoplecontroller/
without having to use a redirect as I still want any error messages from the form validation to appear

I am only giving you an example please arrange according save and return functionality
public function addPerson(){
$this->load->model('people_model'); // load model
// validation
$this->form_validation->set_rules('personName', 'personName', 'required|min_length[6]|max_length[150]|trim|xss_clean');
$this->form_validation->set_rules('personPet', 'personPet', 'required|trim|min_length[3]|max_length[30]|xss_clean');
// check validation not clear
if ($this->form_validation->run() == FALSE) {
//if validation fails - returns the peopl view this display error messages
// also set error dat back
// setting up send back values to view
$this->data['personName'] = $this->input->post('personName');
$this->data['personPet'] = $this->input->post('personPet');
// get this->data values as a variable in view like $personName
// load view
$this->load->view("header");
$this->load->view("people page/people_view", $this->data);
$this->load->view("footer");
}
else{ // after validation success
// do your saving db stuff and set success message in session flash and redirect to
$this->people_model->addPerson();
// get and show message flash in your view
$this->session->set_flashdata('message', 'Please check card details and try again');
redirect('results', 'refresh');
}
}

Related

Symfony 2 Form - refresh protection when form is not valid

first of all sorry for my bad english.
The problem is as follows:
I try to do add and edit post in Blog system.
My pseudocode:
private function getPostForm()
{
$form=$this->createFormBuilder()
->add(...
}
public function addPost()
{
$form=$this->getPostForm... (is a createFormBuilder
// form to create new post
// display form to add - send to updatePost
}
public function editPost()
{
$form=$this->getPostForm... (is a createFormBuilder
// get post id and display form to edit post
// send to updatePost
}
public function updatePost()
{
// get data from post and validate
$form->bind(...
// if validate is true => save
if($form->isValid())....
// if not => get errors and display
else {
// redirect and display errors and post data
}
My problem - when form is not valid, I would like redirect user to add/edit post and display errors thanks to user can't refresh page (eg. F5 key) when data will be sent and not valid.
How to do it correctly?
Maybe, you should do like this. If all is correct do update and redirect, if validation fail display view again
public function updatePost()
{
....
if($form->isValid()){
//yours update logic
return $this->redirect(..);
}
return $this->render('create.html.twig', array(
'form' => $form->createView();
));
}

How to use Flash messages in fat free framework?

I am trying to make an small app so I have choosen Fat Free Framework. I need to show some messages based on successful or error. Suppose if I want to add an user then if successfully added show message that user has been added successfully or if not show error message that user cannot be added. I cannot figure it out. Here is my UsersController code
public function index(){
$user = new User($this->db);
$this->f3->set('users',$user->all());
//there should be a way to decide if its error message or success and after display,
//it shouldn't be displayed again for the same task.
//or may be it should be check in view file, I don't know where is the correct place
// to do it
$this->f3->set('page_head','User List');
$this->f3->set('view','users/list.htm');
}
public function create(){
if($this->f3->exists('POST.create')){
$user = new User($this->db);
$user->add();
//set session here to show in view file after redirect to list page
$this->f3->reroute('/users');
} else{
$this->f3->set('page_head','Create User');
$this->f3->set('view','users/create.htm');
}
}
My flash messages controller looks like this: https://github.com/ikkez/f3-flash/blob/master/lib/flash.php
To set a message i do:
if ($this->resource->updateProperty(array('_id = ?', $params['id']), 'published', true)) {
\Flash::instance()->addMessage('Your post was published. Hurray!', 'success');
} else {
\Flash::instance()->addMessage('This Post ID was not found', 'danger');
}
$f3->reroute('/admin/post');
To render the messages i include this template in my layout https://github.com/ikkez/fabulog/blob/master/app/ui/templates/alert.html which calls a function that dumps and clears all messages, so they will only be displayed once. You can also use the SESSION in a template token like {{#SESSION.flash}} and use it for <repeat> in the template.

Submitting form to itself and echoing validation errors in CodeIgniter

I had few forms in my project, they were submitted to public function's like site.com/email => site.com/validate_email, but then I realized that that's not what I want.
Now I need to make them submit to themselfs ,check and display validation errors.
What is the appropriate way to do this? Check for emptyness of $_POST and then call my new _validate_email(//that will return true or false) if post isn't empty?
Or something else not that noobish?:)
for example:
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim|xss_clean|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run())
{
//some stuff here
}
else
{
$this->load->view('login'); //or redirect()?
}
view:
<?php $this->load->view('header'); ?>
<div class="form-container">
<?=$this->form_validation->validation_errors();?>
<?php
$form_atr = array(
'id' => 'form-set'
);
echo form_open('main/login_validation', $form_atr);//this should be 'main/login'
?>
<div class="header">
/*
here goes other parts of form
*/
</div><!--END form-container -->`
<?php $this->load->view('footer'); ?>
So, basicaly i need to combine login() and login_validation(), but make it so that when user`s input incorrect i get reloaded page of the same view with the same URL and get validation errors displayed.
I've tried to put code of validation into the same function that displays form, but I can't figure out how to redirect or reload the view to show val.errors if any.
So, I think this way is correct(It really should be):
I made my login_validation() private by adding '_' before it, like so _login_validation()
Than I added an if() statement that contains $_POST form variables and i am cheking them with php isset() function, that way the code can determine when user submitted a form. And after all that I just call _login_validation() if inputs are set or load again my login view if not.
public function login()
{
if(isset($_POST['password']) && isset($_POST['email']))
{
$this->_login_validation();
}
else
{
$this->load->view('login');
}
}
and dont forget to process your form so it would submit to the same URL:
echo form_open('', $form_atr);
Hope that will help someone someday.
First of all, validation_errors() is one kind of flash data, so whenever you redirect the page with error the validation errors will be displayed, if you reload it second time it will not be displayed.
From your question i could not understand, do you want to show the errors or not.
if you want to show the errors:
then just redirect the page to login and in the login view add a alert div.
if you don't want to show the errors:
then just remove the alert div.
*i don't see any alert div in your login view, if validation errors are still displayed then may be alert div is in the header view

codeigniter flashdata not clearing

I'm a newbie to codeigniter and I'm creating a project in which users are created and managed. here I'm using flashdata to display the temporary messages like "user created",etc.,
My code to set flash data is
$this->session->set_flashdata('message', 'User Created.');
In my view I called it as
$this->session->flashdata('message');
My problem is that when the user is created,flashdata is displayed and when i click home link the flash data is still available but when i click refresh/home again it disappears. I want it to be cleared when i click the home link for the first time itself. Is there a way to code it??.
Flashdata will only be available for the next server request, and are then automatically cleared.
if($user_created)
{
$this->session->set_flashdata('success', 'User created!');
redirect('login');
}
else
{
redirect('register');
}
if you want to clear set_flash in controller or another view file, then you can use this simple code.
$this->session->set_flashdata('error', 'User not found...'); //create set_flash
unset set_flash
//echo "<pre>"; print_r($_SESSION); die; //for check
if(isset($_SESSION['error'])){
unset($_SESSION['error']);
}
You should redirect after user created. Then when next time you click on home link it will not appear, try this,
$this->session->set_flashdata('message', 'User Created.');
redirect(base_url().'home.php');// you can change accordingly
The flashdata is supposed to display once.
And it gets disappears on page refresh.
So, if you redirect the page to another, it should work.
If you do not refresh the page, you can do it through jQuery.
Say your div displaying flash:
<div id="flash-messages">Success Message</div>
Write jQuery:
<script type="text/javascript">
$(function(){
$("#flash-messages").click(function(){$(this).hide()});
});
</script>
You must redirect the page somewhere after $this->session->set_flash('item','value');
Example:
if ($this->form_validation->run() == FALSE){
$this->session->set_flashdata('error',validation_errors());
redirect(base_url().'user/login');
}
else{
$this->session->set_flashdata('success','Thank you');
redirect(base_url().'user/login');
}
Usually developer make a mistake when they submit data to same page. They set flash data but forget to redirect.
You can use a Ajax framework for automatically hide the flash message.Also their contains all of the flash operation.
You can get more information from here.
https://github.com/EllisLab/CodeIgniter/wiki/Ajax-Framework-For-CodeIgniter
If nothing else helps, just extend the Session library and add a clear_flashdata function.
<?php defined('BASEPATH') or exit('No direct script access allowed');
// application/libraries/Session/MY_Session.php
class MY_Session extends CI_Session
{
public function __construct(array $params = array())
{
parent::__construct($params);
}
/**
* Clear flashdata
*
* Legacy CI_Session compatibility method
*
* #param mixed $data Session data key or an associative array
* #return void
*/
public function clear_flashdata($data)
{
$this->set_userdata($data, null);
}
}

HTTP 500 error using CodeIgniter Form Validation callback functions

So I'm trying to use a callback function with the Form_validation library in CodeIgniter (v2.1.4) to check whether a user with a given username or email exists in the database before creating a new user.
login.php (Controller)
function create_member()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|callback_value_check[USERNAME]');
if($this->form_validation->run() != FALSE)
{
// Validation passed; create the new user.
$this->load->model("members_model");
if($query = $this->members_model->create_member())
{
// Load the success page view.
}
else
{
// Reload the signup page view.
}
}
else
{
// Reload the signup page view.
}
}
function _value_check($value, $column)
{
$this->load->model("members_model");
if($this->members_model->check_exist_value($column, $value))
{
$this->form_validation->set_message('value_check', '%s is already taken.');
return FALSE;
}
else
{
return TRUE;
}
}
members_model.php (Model)
function check_exist_value($column, $value)
{
$this->db->where($column, $value);
$result = $this->db->get('MEMBERS');
if($result->num_rows() > 0)
{
// A user with that unique value already exists in the database.
return TRUE;
}
else
{
// There is no user with that unique value in the database.
return FALSE;
}
}
As seen in the code above, I'm only currently testing for an existing username. The standard validation messages appear correctly (i.e. required, min_length, etc). However, if I enter a value that I know to be already in the database (meaning the custom callback validation function should fail) I instead get an HTTP 500 error (Chrome's default 'Server error' page).
Does anyone have any insight as to why I'm getting an HTTP 500 error instead of seeing my custom error message?
I don't know why you are using you callback for the email/username unique check when codeigniter already provides this functionality in the form_validation class just add the unique rule check in the validation rules with the table name and column that has the emails/usernames also provide the table is column
$this->form_validation->set_rules('username', 'Username',
'trim|required|min_length[4]|unique[tablename.column_email_username,tablename.id]');
$this->form_validation->set_rules('username', 'Username',
'trim|required|min_length[4]|is_unique[tablename.column_email_username]');
Hope unique[tablename.column_email_username,tablename.id] does the job and you will not face the server error
OR try this for is_unique
Ahaha, turned out there was a type in the section reloading the view when the validation failed. Just needed to take a break and re-read through what I had to spot it!

Categories