Getting ID from previous page to field on next page (CodeIgniter) - php

Basically all I want to do is from my view page which is displaying a specific article then having a delete link to a page with a field and a button for deleting that article with the id displayed in that field.
I have had a go at this for the last couple of days trying to put the id in the URL link i.e "delete?id=20" and trying to access it with a $_GET and then I tried "delete/20" and URI segments.
Then I attempted at using sessions etc but i am not sure which is best as I haven't got any of them working.
I have decided to show my untouched code and start from scratch here is my code:
view.php
<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo '<p>'.$news_item['text'].'</p>';
?><br><br>
<a href="http://website.com/CodeIgniter/index.php/news">
Go to latest news</a>
Delete<br>
delete.php
<h2>Delete a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/delete') ?>
<form>
<label for="delete">Article Number</label><br>
<input name="id" class="resizedTitlebox" value="id" /><br>
<br>
<input type="submit" name="submit" value="Delete news item" /></form>
news.php (controller)
<?php
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
public function view($slug)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
public function delete() {
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Delete news item';
$this->form_validation->set_rules('id', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/delete');
$this->load->view('templates/footer');
}
else
{
$data['id'] = $this->news_model->delete('id');
$this->load->view('news/success');
}
}
}
news_model.php (model)
<?php
class News_model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function get_news($slug = FALSE){
$this->load->helper('text');
if ($slug === FALSE){
$this->db->order_by('id', 'desc');
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'id' => $this->input->post('id'),
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text'));
return $this->db->insert('news', $data);
}
public function delete ($id) {
$this->db->where('id',$this->input->post('id'));
$this->db->delete('news');
}
}
routes.php (config)
$route['news/(:any)'] = 'news/view/$1';
$route['news/delete'] = 'news/delete';
$route['news'] = 'news';
$route['default_controller'] = 'news';
$route['404_override'] = '';
Thanks in advance for any help given!
#jeroen answer
"You are not passing any value in the delete link; you should add an ID either to the path or the query string" - I assume you mean like
Delete
So using article_id. Then I can define article_id in the delete controller? I am not sure how this can be done.
answer:
$this->input->get(article_id)

Your delete procedure seems strange and has some errors:
You are no specifying a method in your form, so that will default to GET but in your delete function you use $this->input->post('id'). You should change your form to <form action="" method="POST">;
You are sending a variable to your delete function that you don't use: $id. This is a string in your controller although the name in the model seems to suggest an ID. But you are not using it anyway...
You are expecting a return value from the delete function when you call it in your controller but you don't return anything from your function.
You are not passing any value in the delete link; you should add an ID either to the path or the query string, but be careful not to use the same name $id if you use the same controller as the form will validate without the confirmation;
You are not getting any value for the ID in the delete controller and passing it to the view to fill the value of your ID field.
By the way, there is no input type id but that should not cause any problems as it defaults to text.

I think their is no need of delete view page.You can directly delete news item from your news list page
Delete<br>
instead of this line use this
<a href = "<?php echo site_url("news/delete/".$news_item['id']); ?>Delete</a>
And in your controller
public function delete($id){
$this->news_model->delete($id);
$this->load->view('news/success');
}
And in your model use this
function Delete($id){
$this->db->where('id', $id);
if($this->db->delete("news"))
return true;
else
return false;
}

Related

Unable to pass data from controller to view in codeigniter

I'm having issues passing data from my controller to my view. I have a contenteditable div that I am saving the contents of to my database; I want to then display that in the view.
My controller
{
function __construct(){
parent::__construct();
$this->load->database();
$this->load->model('view_data');
$data = array();
}
public function index(){
$data['contactMe'] = $this->input->post('data');
$this->db->update('content', $data);
$results = $this->view_data->loadData();
$data['contactMeData'] = $results;
$this->load->view('pages/home', $data);
}
}
My model
<?php
class View_data extends CI_Model{
function __construct(){
parent::__construct();
}
public function loadData(){
$this->db->where('contactMe');
$query = $this->db->get('content');
return $query->result_array();
}
}
My view
<div class="w-100" ondblclick="makeEditable(this)" onblur="makeReadOnly(this)" contenteditable="true" id="contactMe">
<?php
foreach($contactMeData as $contact){
echo $contact;
}
?>
</div>
<button id="editBtn" type="submit" value="">Save changes
</button>
Every time I reload the page it replaces the data already in the database and I just get a blank div. I'm unable to view the data that was in the database to begin with.
try to add parameter on where
$this->db->where('contactMe',$parameter);
try to add field name on your view
echo $contact['field_name'];
This might be because every time you open the URL it updates the table, so you need a condition to check if POST request was made or not and then update the column
public function index(){
if($this->input->post()){ // check for post request
$data['contactMe'] = $this->input->post('data');
$this->db->update('content', $data); // try writing db queries in model
}
$results = $this->view_data->loadData();
$data['contactMeData'] = $results;
$this->load->view('pages/home', $data);
}
See, if it helps you.

URI routing in CodeIgniter causes 404 error

Second EDIT - Found the Problem, and answered it as well.
First Edit - added my Post_model.php file as well for clearer explanation of my code.
I am trying to redirect a Blogs slug to a separate page where I can show the entire blogs content.
here's an example slug
http://localhost/aag/posts/test-one
Here's the Posts controller
<?php
class Posts extends CI_Controller {
public function index(){
// Shows a blog listing
}
public function view($slug = NULL){
$data['post'] = $this->post_model->get_posts($slug);
if(empty($data['post'])){
show_404();
}
$data['title'] = $data['post']['title'];
$this->load->view('templates/header');
$this->load->view('posts/view', $data);
$this->load->view('templates/footer');
}
}
The posts/view.php file
<h2><?php echo $post['title']; ?></h2>
<small class="post-date">Created on <?php echo $post['created_at']?></small><br>
<div class="post-body">
<?php echo $post['body']; ?>
</div>
the Post_model.php
class Post_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function get_posts($slug = FALSE)
{
if ($slug === FALSE) {
$query = $this->db->get('posts');
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => '$slug'));
return $query->row_array();
}
}
routes.php
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['(:any)'] = 'pages/view/$1';
Okay, so years of writing mysqli queries made me do this mistake. In my Post_model.php I am getting the data where (DB column field) slug should match the $slug that gets passed in, but I surrounded the slugs inside single quotes that was causing the error. Here's the working code now.
class Post_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function get_posts($slug = NULL)
{
if ($slug === NULL) {
$query = $this->db->get('posts');
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->row_array();
}
}
TLDR: Don't encapsulate your passed in arguments inside quotes.

How to update form of particular id in codeigniter?

I am new to codeigniter. I am stuck at update my form data. i am using one source code from internet but its not working for me. I am done with fetching data from multiple tables on one form.Now i want to update that form.I am sharing my code step by step so you will understand it.
Controller for fetching data in form:
public function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load->model('user_model');
$this->load->library('session');
}
function login_user(){
$user_login=array(
'USER_NAME'=>$this->input->post('user_email'),
'PASSWORD'=>($this->input->post('user_password')),
'PIN'=>($this->input->post('user_pin'))
);
$data=$this->user_model->login_user($user_login['USER_NAME'],$user_login['PASSWORD'],$user_login['PIN']);
if($data)
{
$this->session->set_userdata('user_id',$data['USER_ID']);
$this->session->set_userdata('user_name',$data['USER_NAME']);
$this->session->set_userdata('employee_id',$data['EMPLOYEE_ID']);
$this->session->set_userdata('nationality',$data['NATIONALITY']);
$this->session->set_userdata('EMPLOYEE_NAME',$data['EMPLOYEE_NAME']);
$this->session->set_userdata('EMPLOYEE_NUMBER',$data['EMPLOYEE_NUMBER']);
$this->session->set_userdata('DATE_OF_BIRTH',$data['DATE_OF_BIRTH']);
$this->session->set_userdata('JOINING_DATE',$data['JOINING_DATE']);
$this->session->set_userdata('CURRENT_LOCATION',$data['CURRENT_LOCATION']);
$this->session->set_userdata('SEX',$data['SEX']);
$this->session->set_userdata('ADDRESS',$data['ADDRESS']);
$this->session->set_userdata('COMPANY_EMPLOYEE_NUMBER',$data['COMPANY_EMPLOYEE_NUMBER']);
$this->session->set_userdata('PHONE',$data['PHONE']);
$this->session->set_userdata('MOBILE',$data['MOBILE']);
$this->session->set_userdata('EMAIL_ADDRESS',$data['EMAIL_ADDRESS']);
$this->session->set_userdata('ALTERNATE_EMAIL',$data['ALTERNATE_EMAIL']);
$this->session->set_userdata('WORKING_HOURS',$data['WORKING_HOURS']);
$this->session->set_userdata('NOK',$data['NOK']);
$this->session->set_userdata('NOK_CONTACT_NUMBER',$data['NOK_CONTACT_NUMBER']);
$this->session->set_userdata('EMPLOYMENT_STATUS_ID',$data['EMPLOYMENT_STATUS_ID']);
$this->session->set_userdata('DESIGNATION_NAME',$data['DESIGNATION_NAME']);
$this->session->set_userdata('CURRENT_ORG_ID',$data['CURRENT_ORG_ID']);
$this->session->set_userdata('COS_NUMBER',$data['COS_NUMBER']);
$this->session->set_userdata('VISA_START_DATE',$data['VISA_START_DATE']);
$this->session->set_userdata('VISA_END_DATE',$data['VISA_END_DATE']);
$this->session->set_userdata('DESCRIPTION',$data['DESCRIPTION']);
$this->session->set_userdata('SKILLS',$data['SKILLS']);
$this->session->set_userdata('YR_OF_EXPERIENCE',$data['YR_OF_EXPERIENCE']);
$this->load->view('layouts/index.php');
}
else{
$this->session->set_flashdata('error_msg', 'Error occured,Try again.');
$this->load->view('layouts/login.php');
}
}
model for fetching data:
class User_model extends CI_model{
public function login_user($email,$pass,$pin){
$this->db->select('*');
$this->db->from('app_users');
$this->db->where('USER_NAME',$email);
$this->db->where('PASSWORD',$pass);
$this->db->where('PIN',$pin);
$this->db->join('employee_details', 'app_users.EMPLOYEE_ID = employee_details.EMPLOYEE_ID', 'LEFT');
$this->db->join('employee_master', 'app_users.EMPLOYEE_ID = employee_master.EMPLOYEE_ID', 'LEFT');
$this->db->join('designation_master', 'employee_details.DESIGNATION_ID = designation_master.DESIGNATION_ID', 'LEFT');
$this->db->join('employee_visa_details', 'employee_details.EMPLOYEE_ID = employee_visa_details.EMPLOYEE_ID', 'LEFT');
$this->db->join('visa_status_master', 'employee_visa_details.VISA_STATUS_ID = visa_status_master.VISA_STATUS_ID', 'LEFT');
$this->db->join('employment_status_master', 'employee_details.EMPLOYMENT_STATUS_ID = employment_status_master.EMPLOYMENT_STATUS_ID', 'LEFT');
$this->db->join('employee_skills', 'employee_details.EMPLOYEE_ID = employee_skills.EMPLOYEE_SKILLS_ID', 'LEFT');
if($query=$this->db->get())
{
return $query->row_array();
}
else{
return false;
}
}
}
Above files are working fine. i can see data of particular user in form view.
Now i want to update that data so i write below code:
Controller:
class Personal_details extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load->model('user_model');
$this->load->model('personal_details_model');
$this->load->library('session');
}
public function update_personal_details(){
$products = new personal_details_model;
$products->update_personal_details($id);
redirect('/responsibilities/personal_details/');
}
}
model for the same:
class Personal_details_model extends CI_model{
public function update_personal_details($id)
{
$data=array(
'EMPLOYEE_NAME' => $this->input->post('emp_name'),
'DATE_OF_BIRTH'=> $this->input->post('dob'),
'JOINING_DATE' => $this->input->post('joining_date'),
);
if($id==0){
return $this->db->insert('employee_master',$data);
}else{
$this->db->where('EMPLOYEE_ID',$id);
return $this->db->update('employee_master',$data);
}
}
}
I dont understand how to write code to update above all tables.
My form view is like this:
<form action="<?php echo site_url('personal_details/update_personal_details');?>" method="post" class="form-horizontal" >
<button type="submit" class="btn btn-info">Edit</button>
<button type="submit" class="btn btn-danger">Cancel</button>
I am getting this error on click edit button:
error on update
First you have to get form data in Personal_details controller then you will pass that data to the Personal_details_model. Second no need to create new object for your model in update_personal_details() function you already loaded personal_details_model in your constructor.

Codeigniter Form Dropdown Error After Validation

I'm trying to adapt the form_dropdown to my form in codeigniter. When i'm adding a new page, it doesn't show any errors in parent dropdown section, but after form validation, for instance if user forgets to enter the title label, if its empty or, after validation it gives foreach error in the dropdown section.
I've read that, the second variable must be array and so on for the form_dropdown. But mine is array and not giving any errors in the page before validation. So i can't figure the problem out.
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: helpers/form_helper.php
Line Number: 331
MY_Controller :
class MY_Controller extends CI_Controller{
public $data = array();
function __construct(){
parent::__construct();
}
}
Admin Controller :
class Admin_Controller extends MY_Controller{
function __construct(){
parent::__construct();
$this->data['meta_title'] = 'My Website Control Panel';
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters(' <div class=" alert alert-danger alert-block" ><span class="glyphicon glyphicon glyphicon-minus-sign"></span> ', '<span class="close" data-dismiss="alert">×</span></div>');
$this->load->library('session');
$this->load->model('user_m');
$exceptions = array('admin/user/login', 'admin/user/logout');
if(in_array(uri_string(),$exceptions) == FALSE){
if($this->user_m->loggedin() == FALSE){
redirect('admin/user/login');
}
}
}
}
Controller :
class Page extends Admin_Controller{
public function __construct(){
parent::__construct();
$this->load->model('page_m');
}
public function index(){
$this->data['pages'] = $this->page_m->get_with_parent();
$this->data['subview'] = "admin/page/index";
$this->load->view('admin/_layout_main',$this->data);
}
public function edit ($id = NULL)
{
// Fetch a page or set a new one
if ($id) {
$this->data['page'] = $this->page_m->get($id);
count($this->data['page']) || $this->data['errors'][] = 'Not found.';
}
else {
$this->data['page'] = $this->page_m->get_new();
}
// Pages for dropdown
$this->data['pages_no_parents'] = $this->page_m->get_no_parents();
// Set up the form
$rules = $this->page_m->rules;
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->page_m->array_from_post(array('title', 'slug', 'body','keywords','description','parent_id'));
$this->page_m->save($data, $id);
redirect('admin/page');
}
// Load the view
$this->data['subview'] = 'admin/page/edit';
$this->load->view('admin/_layout_main', $this->data);
}
}
Model:
public function get_no_parents ()
{
// Fetch pages without parents
$this->db->select('id, title');
$this->db->where('parent_id', 0);
$pages = parent::get();
// Return key => value pair array
$array = array(
0 => ''
);
if (count($pages)) {
foreach ($pages as $page) {
$array[$page->id] = $page->title;
}
}
return $array;
}
View :
<?=form_dropdown('parent_id', $pages_no_parents, set_value('parent_id', $pages_no_parents, $this->input->post('parent_id') ? $this->input->post('parent_id') : $page->parent_id);?>
In the if condition $this->form_validation->run == false write:
$this->data['pages_no_parents'] = $this->page_m->get_no_parents();
you can try something like this
if($this->form_validation->run() == FALSE)
{
redirect('your_controller/function','refresh');
}
UPDATE
so instead of redirect do load view like
$this->load->view('admin/_layout_main', $this->data);
and in view page do one thing
<?php echo validation_errors(); ?>
please let me know if you face any problem.
As ahmad mentioned, i think i was overwriting something, and after removing set value, and changed view to this, it's now okay.
<?php echo form_dropdown('parent_id', $pages_no_parents, $this->input->post('parent_id') ? $this->input->post('parent_id') : $page->parent_id); ?>
Thanks for all for the comments and answers.

How do I display active record in codeigniter with multiple controllers?

I am building my comment module and trying to get the active records to display on view. Seems simple however I have a lot going on and using a separate model and controller then what the view is being generated from.
So I have a profile page ( where I'm trying to get the results to display )
Controller:
public function profile()
{
$this->load->helper('url'); //Include this line
$this->load->helper('date');
$this->load->library('session');
$this->load->library('form_validation');
$session_id = $this->session->userdata('id'); //Ensure that this session is valid
//TRYING TO MAKE A VARIABLE WITHT THE $_GET VALUE
$user_get = $this->uri->segment(3); // Modify this line
// LOAD THE CORRECT USER
$this->load->model('account_model');
$user = $this->account_model->user($user_get); //(suggestion) you want to pass the id here to filter your record
$data['user'] = $user;
$data['session_id'] = $session_id;
if($user_get != $user['id'] || !$user_get)
{
$data['main_content'] = 'account/notfound';
$this->load->view('includes/templates/profile_template', $data);
}
else
{
if($user_get == $session_id) //Modify this line also
{
$data['profile_icon'] = 'edit';
}
else
{
$data['profile_icon'] = 'profile';
}
$sharpie = $this->sharpie($user);
$data['sharpie'] = $sharpie;
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/profile_template', $data);
}
}
Now I have a new controller for my comments I'm trying to display:
public function airwave() {
$this->load->helper('date');
$this->load->library('session');
$airwave_get = $this->uri->segment(3);
$this->load->model('community_model');
$airwave = $this->coummunity_model->airwave($airwave_get);
$data['airwave'] = $airwave;
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/main_page_template', $data);
}
with this model:
public function airwave($id=null)
{
if(is_null($id)) {
$session = $this->session->userdata('is_logged_in');
$commenter_id = $this->session->userdata('id');
}else{
$commenter_id = intval($id);
}
$query = $this->db->query("SELECT * FROM airwaves_comments WHERE from_id=$commenter_id");
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data[0];
//above returns the single row you need to the controller as an array.
//to the $data['user'] variable.
}
}
and trying to display it on this view ( which is generated by the profile function )
<div class="profile_airwave_comment_text">
<?php echo $airwave['comment'];?>
</div>
I just can't seem to get it to pass the array variable I've created properly to that view?
thanks in advance.
The first glaring thing I see wrong is in you model's airwave function:
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data[0];
You are assuming that there will only be one result in your query, so if there are more or less than one, your $data array will bever be set.
Also, even then you are only returning the first element in the array. I am not seeing anywhere in your question that you want to return only one.
Finally, in your view, if you now return the full array, and not only one element, you will have to do a foreach statement.
EDIT: please see suggested solution.
In your model, don't worry about the check for the amount of data in the result array. This will come later. Simply do:
return $query->result_array();
Now, keep your controller as is, but adapt your view:
<div class="profile_airwave_comment_text">
<?php
if (isset($airwave) && is_array($airwave) && !empty($airwave))
{
foreach ($airwave as $wave)
{
echo $wave['comment'];
}
}
else
{
echo 'No comments found...';
}
?>
</div>
This should work, and if not, at least let you know that no comments were fond, and thus check your database.
HTH!
If your using HMVC, simply call the module from inside the profile view, ie:
echo Modules::run('comments/profileComments', $user->id);
Else:
You would need to create a new method in the loader class, to load in the controller seperate from routing.
If your really after a quick fix until you come up with a better alternative, you could(depending if both controllers live in the same directory) just include the 'comments' controller in your 'profile' controller and try something like this:
{Cons: CI Pagination wont work!}
application/controllers/profile.php
include 'Comments' . EXT;
class Profile extends CI_Controller{
public function __construct ()
{
parent::__construct () ;
}
public function index( $user_id ){
$commentsPartialView = call_user_func_array(array(new Comments(), "getProfileComments"), array($user_id));
return $this->load->view($this->template, array(
'view' => 'profiles/_index',
'comments' => $commentsPartialView
));
}
}
-
application/controllers/Comments.php
class Comments extends CI_Controller{
public function __construct ()
{
parent::__construct () ;
}
public function getProfileComments( $user_id ){
$user_comments = ''; //pull from DB
//set third param to TRUE for partial view, without main template
return $this->load->view('comments/show', array(
'user_comments' => $user_comments
), TRUE);
}
}

Categories