Redirect , POST and Flashdata issue in Codeigniter - codeigniter

i am developing an application where i need some suggestions. Here is the detail of the problem.
public function form()
{
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
if($data = $this->input->post()){
$result = $this->form_validation->run();
if($result){
if($id > 0){
// here update code
}else{
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}
}else{
//$this->call_post($data);
$this->session->set_flashdata('message','The Red fields are required');
$this->view = FALSE;
$this->redirect = "mycontroller/form/$id";
}
}else{
$row = $this->mymodel->fetch_row($id);
$this->data[]= $row;
}
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$return = call_user_func_array(array($this, $method),$parameters);
}else{
show_404();
}
if(strlen($this->view) > 0)
{
$this->template->build('default',array());
}else{
redirect($this->redirect);
}
}
Here you can see how i am trying to reload the page on failed validation.
Now the problem is that i have to display the flash data on the view form which is only available after redirect and i need to display the validation errors to which are not being displayed on redirect due to the loss of post variable. If i dont use redirect then cant display flashdata but only validation errors. I want both of the functionalities togather. I have tried even creating POSt again like this
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
Which i commented out in the formmethod.How can i achieve this.

Here's a thought.
I think you can add the validation error messages into the flash data. Something like this should work:
$this->session->set_flashdata('validation_error_messages',validation_errors());
Notice the call to the validation_errors function. This is a bit unconventional, but I think it should work. Just make sure that the code are executed after the statement $this->form_validation->run(); to make sure the validation error messages are produced by the Form Validation library.

well i have little different approach hope will help you here it is
mycontroller extend CI_Controller{
function _remap($method,$params){
switch($method){
case 'form':
$this->form($params);
break;
default:
$this->index();
break;
}
}
function form(){
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
$this->form_validation->set_rules('name','Named','required|trim');
$this->form_validation->set_rules('email','email','required|valid_email|trim');
// if validation fails and also for first time form called
if(!$this->form_validation->run()){
$this->template->build('default',array());
}
else{ // validation passed
$this->save($id)
}
}
function save($id = 0){
$data = $this->input->post();
if($id == 0){
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}else{
// update the field
$this->session->set_flashdata('message','The Red fields are required');
}
redirect("mycontroller/index");
}
}
your form/default view should be like this
<?
if(validation_errors())
echo validation_errors();
elseif($this->session->flashdata('message'))
echo $this->session->flashdata('message');
echo form_open(uri_string());// post data to same url
echo form_input('name',set_value('name'));
echo form_input('email',set_value('email'));
echo form_submit('submit');
echo form_close();
try it if you face any problem post here.

Related

how to check if username already exists in codeigniter my error

My controler cod is:
function register()
{
if(isset($_POST['register'])){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if($this->form_validation->run () == true){
echo 'Form Validate';
$data = array(
'username'=>$_POST['username'],
'email'=>$_POST['email'],
'password'=>strtoupper(hash('whirlpool',$_POST['password']))
);
$this->db->insert('accounts',$data);
$this->load->model("usuarios_model");
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}
}
}
$this->load->view("painel/register");
}
[![enter image description here][2]][2]
It registers an user even though the username already exists.
Where is the mistake?
You can use is_unique rule in your form_validation library.
$this->form_validation->set_rules('username','Username','required|is_unique[table.column]');
You have mistake in your model in where condition it will be small later of username but you used Username.
use this code in your model.
function check_user_exist($username){
$this->db->wehre('username',$username);
$this-db->from('accounts');
$query= $this->db->get();
if($query->num_rows() > 0){
return true;
}else{
return false;
}
}
and also controller data insert after user check:
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}
You can easily achieve this using call_back function in validation. From Codeigniter Docs
Controller
function register() {
if ($this->input->post('register')) {
$this->form_validation->set_rules('username','Username','required|callback_checkUserName');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if ($this->form_validation->run() == true) {
$data = array(
'username '=> $this->input->post('username'),
'email' => $this->input->post('email'),
'password' => strtoupper(hash('whirlpool', $this->input->post('password')))
);
$this->db->insert('accounts',$data);
echo 'success';
exit();
} else {
echo validation_errors(); die; // check errors
}
}
$this->load->view("painel/register");
}
// call back validate function
function checkUserName($userName){
if ($this->usuarios_model->checkUserexist($userName) == false) {
return true;
} else {
$this->form_validation->set_message('checkUserName', 'This userName already exist!');
return false;
}
}
MODEL
function checkUserexist($userName) {
$this->db->where('username', $userName);
$this-db->from('accounts');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return true;
}
return false;
}
This my code which I used in one of my projects replace the words with your code:
$this->form_validation->set_rules('companyname','Company Name','trim|required|callback_companyname_exist');
Here is above callback function:
function companyname_exist($str) {
$this->db->where('company_name', $str);
$this->db->where('user_type','Shop');
$prod = $this->db->get('grs_user');
if ($prod->row()) {
$this->form_validation->set_message('companyname_exist', 'This Company name is already Available.');
return FALSE;
} else
return TRUE;
}
You can used this for already register email check also.

Joomla 2.5 method save()

Is there a way to show the changed values after saving within the Joomla save method?
For example, when I edit a "maxuser" field and save it, I´d like to show the old and the new value.
I tried this by comparing "getVar" and "$post", but both values are the same.
function save()
{
...
$maxuser1 = JRequest::getVar('maxuser');
$maxuser2 = $post['maxuser'];
...
if($maxuser1 != $maxuser2) {
$msg = "Not the same ...";
}
...
}
It's better to override JTable, not the Model. Heres sample code:
public function store($updateNulls = false) {
$oldTable = JTable::getInstance(TABLE_NAME, INSTANCE_NAME);
$messages = array();
if ($oldTable->load($this->id)) {
// Now you can compare any values where $oldTable->param is old, and $this->param is new
// For example
if ($oldTable->title != $this->title) {
$messages[] = "Title has changed";
}
}
$result = parent::store($updateNulls);
if ((count($messages) > 0) && ($result === true)){
$message = implode("\n", $messages);
return $message;
} else {
return $result;
}
}
This will return message string if there are any, true if there are no messages and save succeeded and false if saving failed. So all you have to do is check returned value in model and set right redirect message.
In the controller you can use the postSaveHook which gives you access to the validated values.

Codeigniter - Passing multiple parameters

I am trying to pass multiple parameters to my model from my controller. It seems that the $scholId that I am trying to pass won't go through to the model after I submit the form. However, the $userId goes through to the database just fine. Is there something wrong with $this->uri->segment(4) that won't pass through correctly?
function apply()
{
$this->load->helper('form');
$this->load->library('form_validation');
$scholId = $this->uri->segment(4);
$userId = '2'; //User query -> this will be taken from session
$this->data['scholarship'] = $this->scholarship_model->getScholarship($scholId);
$this->data['title'] = "Apply";
$this->form_validation->set_rules('essay', 'Essay', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $this->data);
$this->load->view('student/page_head', $this->data);
$this->load->view('student/form', $this->data);
$this->load->view('templates/footer', $this->data);
}else{
// Validation passes
$this->users_model->applySchol($userId,$scholId);
redirect('/scholarships');
}
}
you need to check up the segment whether it exists or not before passing it Like:
if ($this->uri->segment(4) === FALSE)
{
$schoId = 0; //or anything else so that you know that does not exists
}
else
{
$schoID= $this->uri->segment(4);
}
or simply:
$product_id = $this->uri->segment(4, 0);
//which will return 0 if it doesn't exists.

How to prevent code duplication for CodeIgniter form validation?

This is sample of function in the Staff controller for this question
function newStaff()
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
function add_newStaff()
{
//when user submit the form, it will call this function
//if form validation false
if ($this->validation->run() == FALSE)
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
else
{
//submit data into DB
}
}
From the function add_newStaff(), i need to load back all the data from database if the form validation return false. This can be troublesome since I need to maintain two copy of codes. Any tips that I can use to prevent this?
Thanks.
Whats preventing you from doing the following
function newStaff()
{
$data = $this->_getData();
$this->load->view('staff/newstaff', $data);
}
function add_newStaff()
{
//when user submit the form, it will call this function
//if form validation false
if ($this->validation->run() == FALSE)
{
$data = $this->_getData();
$this->load->view('staff/newstaff', $data);
}
else
{
//submit data into DB
}
}
private function _getData()
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
return $data;
}
Alternately you change the action your form submits to so that it points to the same service you use for the initial form request with something like the following. This would also mean that you'd have the POST values retained between page-loads if you wanted to retain any of the submitted values in your form.
function newStaff()
{
// validation rules
if ($this->validation->run() == TRUE)
{
//submit data into DB
}
else
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
}

validate email value in joomla 1.7?

I am developing component and I want to know how to validate email value entered by user using joomla 1.7?
JHTML::_('behavior.formvalidation') without using this method.
Try this,
function validate()
{
jimport('joomla.mail.helper');
$valid = true;
if ($this->_data->email && !JMailHelper::isEmailAddress($this->_data->email))
{
$this->_app->enqueueMessage(JText::_('Invalid Email Address'),'error');
$valid = false;
}
return $valid;
}
function validate($email)
{
jimport('joomla.mail.helper');
$error = false;
if (! $email || ! JMailHelper::isEmailAddress($email))
{
$error = JText::sprintf('Email Corect', $email);
JError::raiseWarning(0, $error);
}
return $error;
}

Resources