How to prevent code duplication for CodeIgniter form validation? - codeigniter

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);
}
}

Related

How to stay on previous page after signin in codeigniter framework

Hii guys i'm new in stackoverflow , if this question is very long please pardon me, This is a Consumer complain website here is a view page called separate_user_admin_reply2.php in this page i want to apply a functionality, If a user without login click on the replay button then Signin.php view page will appear then after login the user come back to the previous page, the previous page link is : http://localhost/A2Zcomplainboard/index.php/Complain/Separate_single_complain_user/COMP008
So what i can do ..please help me (thanks in advance)
The controller is :
public function Separate_single_complain_user($cid)
{
//$cid = $this->input->get('compid');
$this->load->model('Complain_model');
$res = $this->Complain_model->getSingleComplain($cid);
$this->load->model('Replay_Model');
$res1 = $this->Replay_Model->Separate_single_complain_replay($cid);
if($res){
$this->load->view('separate_user_admin_reply2',['res'=>$res,'res1'=>$res1]);
}
}
The model is:
public function getSingleComplain($cid)
{
$complain = $this->db->query("SELECT comp_id,comp_title,comp_description,post_datetime,status,publish_status,comp_catagory,posted_by,id,first_name,email FROM log_tbl l INNER JOIN comp_tbl c ON l.id = c.posted_by WHERE comp_id = '$cid'");
$res = $complain->result_array();
if($res)
return $res;
else
return false;
}
public function Separate_single_complain_replay($cid){
$rep = $this->db->query("SELECT first_name,rep_id,rep_description,rep_datetime,rep_by,rep_against,rep_flag,rating FROM log_tbl l INNER JOIN reply_tbl r ON l.id = r.rep_by WHERE r.rep_against = '$cid 'AND rep_flag = '1'");
$res = $rep->result_array();
if($res)
return $res;
else
return false;
}
enter image description here
This is the view page image
separate_user_admin_reply2.php
And the signin controller is :
public function index()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->load->model('Login_Model');
$data = $this->Login_Model->isvalidate($email,$password);
if($data)
{
$this->load->library('session');
$this->session->set_userdata('email',$data['email']);
$this->session->set_userdata('type',$data['type']);
$this->session->set_userdata('id',$data['id']);
if($data['type']=='User' ){
return redirect('User/index');
}
else
{
return redirect('Admin/adminDashboard');
}
}else{
echo "<script>alert('Details not matched')</script>";
header("refresh:1");
return redirect('Complain/login');
}
}
model:-
public function isvalidate($email,$password)
{
$q = $this->db->where(['email'=>$email,'password'=>$password])
->get('log_tbl');
if($q->num_rows()){
$x = $q->row()->email;
$y = $q->row()->type;
$z = $q->row()->id;
$userData = array('email' => $x, 'type' => $y, 'id' => $z);
return $userData;
}else{
return false;
}
}
signin view page image:
Store the previous page url in session data. You can find a detailed description of how to do that in the codeigniter documentation. When the user successfully logged in, check if the previous page data is set, if so flush it and redirect to it.

What to Show some data On my view but there is a Error In Laravel

Here I am trying to add, Add Comment feature and it's causing a problem to show data.
public function store(Request $request)
{
$chatterreply = new Chatterreply;
$chatterreply->reply = $request->body;
$chatterreply->chatter_post_id = $request->chatter_post_id;
$chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
$chatterreply->save();
$chatterreplies = Chatterreply::where('chatter_post_id',$request->chatter_post_id)->get();
$chatter_editor = config('chatter.editor');
if ($chatter_editor == 'simplemde') {
// Dynamically register markdown service provider
\App::register('GrahamCampbell\Markdown\MarkdownServiceProvider');
}
echo "<pre>"; print_r($chatterreplies); die;
return view('chatter::discussion', compact('chatterreplies','chatter_editor'))->with('chatter_alert','Add Comment Successfully');
}
And Here Is Where I am passing the variable
$chatter = session()->pull('chatter');
return view('chatter::discussion', compact('discussion', 'posts', 'chatter_editor'))->with('chatterreplies',$chatter);

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.

Redirect , POST and Flashdata issue in 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.

Resources