Pagination is not working properly in Codeigniter - codeigniter

I am novice in Codeigniter and I am working on pagination. But there is something wrong in my code. What mistake I have been done in the following code?
I have attached my code snippet below.
Route
$route['default_controller'] = "pages";
$route['default_controller/(:num)'] = "pages/index/$1";
Controller
public function index($page='home')
{
if ( ! file_exists(APPPATH.'views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$config=[
'base_url' => base_url().'/pages/index',
'per_page' => 5,
'total_rows' =>$this->products_model->record_count()
];
$this->pagination->initialize($config);
$data['title'] = ucfirst($page); // Capitalize the first letter
$data['products'] = $this->products_model->get_products($config['per_page'], $this->uri->segment(3));
$data['request'] = 'pages/home';
$this->load->view('templates/content',$data);
}
Model
public function get_products($limit, $offset)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $offset);
$query=$this->db->get('product');
return $query->result_array();
}
public function record_count($value='')
{
return $this->db->count_all("product");
}
View
<?php echo $this->pagination->create_links() ?>
In the View, I am displaying the records from a table. The first page of records displays, but when I click the second page it shows Error
"**404 Page Not Found**"
Any kind of help regarding this issue will be highly appreciated. Thanks in advance.

From your logic, the line "index($page='home') the index method gets the script to display from the parameter passed to it. On the first load, the default page, 'home.php' is matched, but when you select the second page, the CI router and index function look for maybe '1.php' or '2.php' and so on, depending on your paging, do those files exist for every page you request? Otherwise, you should instead check if the page variable is a valid page (e.g non-negative) then continue execution and load the results to your view

Related

Obtain CodeIgniter links that consider routes.php

How can I link pages in my site considering routes.php?
Example:
$route['login'] = 'user/login';
The code above allows me to see "user/login" visiting just "login". But how can I link to that page using the internal route (user/login) and get as a result the "external route" "login".
I think it's important because I could change my URLs just modifiying "routes.php" and linking everything with internal routes.
From a Drupal perspective I can have my internal route "node/1" and the external url could be "about-us". So if I use "l('node/1')" this will return "about-us". Is there a function like "drupal_get_path_alias"?
Right now I can't find anything in the CI docs that point me to the right direction.
Thanks for your help.
You could have a look at using something like
http://osvaldas.info/smart-database-driven-routing-in-codeigniter
This would allow you to have the routes configured in the database. Then if you want to dynamically create you links through a model like this:
class AppRoutesModel extends CI_Model
{
public function getUrl($controller)
{
$this->db->select('slug');
$this->db->from('app_routes');
$this->db->where('controller', $controller);
$query = $this->db->result();
$data = $query->row();
$this->load->library('url');
return base_url($data->slug);
}
public function getController($slug)
{
$this->db->select('controller');
$this->db->from('app_routes');
$this->db->where('slug', $slug);
$query = $this->db->result();
$data = $query->row();
return $data->controller;
}
}
These have not been fully tested but will hopefully give you the general idea.
I hope this helps you :)
Edit------------------------------
You can create a routes_helper.php and add a function like
//application/helpers/routes_helper.php
function get_route($path)
{
require __DIR__ . '/../config/routes.php';
foreach ($route as $key => $controller) {
if ($path == $controller) {
return $key;
}
}
return false;
}
$this->load->helper('routes');
echo get_route('controller/method');
This does roughly what you want although this method does not support the $1 $2 etc vars that can be added to reflect the :num or :any wildcard that exist. You can edit the function to add that functionality but this will point you in the right direction :D
You can do that with .htaccess file:
Redirect 301 /user/login http://www.example.com/login

Why redirect show blank page in model laravel?

I'd like to ask why the following code works, redirects normally, and data is successfully inserted :
CategoriesController :
public function store()
{
$data = Input::all();
$category = new Term;
if($category->saveCategory($data)){
return Redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return Redirect::route('admin_posts_categories')->withError('Failed to add category. #ErrorCode : 13');
}
}
Term model :
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return true;
}else{
return false;
}
}else{
return "#Error Code : 4";
}
}
Where as the following only inserts the data but then shows a blank page and doesn't redirect :
CategoriesController :
public function store()
{
$data = Input::all();
$category = new Term;
$category->saveCategory($data);
}
Term Model
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return redirect::route('admin_posts_categories')->withError('Failed to add category.');
}
}else{
return redirect::route('admin_posts_categories')->withError('#Error Code : 4.');
}
}
Moreover, I'd like to ask a few related questions, does my code conform to correct design patterns, and where should I put the redirect, in the model or in the controller ?
Try this for redirect:
1. return Redirect::back()->withSuccess('Category successfully added.');
OR
2. return Redirect::to(URL::to('admin_posts_categories'))->withSuccess('Category successfully added.');
Add your redirect login inside Controller. Even if you want to put in model (which is not recommended) use Ardent Hook function i.e. afterSave().
First of all never put redirect logic in model. Models are for putting business logic. Second thing check whether you have created route for admin_posts_categories in route.php or not and how you are calling views. If possible post your route code in question.
I recommend not putting redirects in your model. So the first solution would be the best of the two you have.
But back to your problem. It is showing a blank page because your store function is not returning anything. return $category->saveCategory($data); but as previously stated this method is not best practise.
An excellent tip would be to have a look at Laracasts, this will teach you everything you knew, didn't know and more about Laravel.

not able get flashdata in CodeIgniter

Here is my controller code
function index() {
echo $this->session->flashdata('message');
$this->load->view('categoryView');
}
function delete() {
$products = $this->item_model->get_category_id($category_id);
if (count($products)) {
$message = 'Category Name is used by the product. Please change them to another category!';
}
else {
$category_id = $this->product_category_model->delete($category_id);
$message = ($category_id) ? 'Category Deleted Successfully' : 'Failed to Delete Category';
}
$this->session->set_flashdata('message', $message);
redirect('category', 'refresh');
}
After calling the delete function the flashdata has to be set and retrieve that value in index() function of the same controller but I can't.
Am also tried the $this->session->keep_flashdata('message'); before redirect to index function. But still am not get any value in index function.
Also changed $config['sess_expire_on_close'] = FALSE; to $config['sess_expire_on_close'] = TRUE; Still am not get the result.
I am wasted more time(nearly half day). Please anybody help to retrieve the flas data in codeigniter.
There are several probabilities:
1- Check your browser cookie. See if it allows cookies or if any other extension is intervening.
2- Refresh might not send the browser a new request (which thus mean a new URL). Try it for another controller see if it make any change
3- hard code the set_flashdata() with hard-coded value than a variable. set_flashdata("message", "Thank you");
In codeingitor you cannot echo anything in controller.
You have to set in $this->session->flashdata('message'); in view file not in index() function of controller
Try again by putting $this->session->flashdata('message'); in "categoryView" file where you want to display flash message.
You could try:
function set_flashdata_notification($notify_type, $msg, $error_code = null)
{
$ci =& get_instance();
$flashdata_data = set_notification_array($notify_type, $msg, $error_code);
$ci->session->set_flashdata($flashdata_data);
}
function delete() {
$products = $this->item_model->get_category_id($category_id);
if (count($products)) {
set_flashdata_notification('Category Name is used by the product.','Please change them to another category!');
redirect('path_to_view/view','refresh');
}

CodeIgniter view problem

This is my first day playing with CI and I really like it so far but have a problem I can't solve on my own. The issue is that I need to generate single view with two controller functions. One div should include selected row by ID from table A and other div should loop foreach on array from table B.
public function index()//div A
{
$data['query'] = $this->db->get_where('beer', array('id' => 1));
$this->load->view('corp/corp_view', $data);
}
public function loadList() //div B
{
$data['q'] = $this->db->get_where('list', array('id' => 1));
$this->load->view('corp/mentor_list_view', $data);
}
I tried to solve this for few hours by creating another view for loadList() and then including it in the the main view like "$this->load->view()" but I'm getting the values from the index() function query table 'beer' not 'list' table as intended. Again I'm new to this and would appreciate your help.
Thank you for your help.
Thanks for the extra info, i can help yah out now.
In Codeigniter if you want to make a function that is not able to be called by the user just precede it with a '_'. So in your case:
public function index()//div A
{
$data['query'] = $this->db->get_where('beer', array('id' => 1));
$data['query2'] = $this->_mySecondQuery();
$this->load->view('corp/corp_view', $data);
}
public function _mySecondQuery() //div B
{
return $this->db->get_where('list', array('id' => 1));
}
Now in the index page you have access to both queries. Btw, I would not suggest doing much DB work in the controller. DB work is meant to be done in Models. For more info on those see: Codeigniter Models

Codeigniter - accessing variables from an array passed into a page

I have a controller with an index function as follows:
function index()
{
$this->load->model('products_model');
$data['product'] = $this->products_model->get(3); // 3 = product id
$data['product_no'] = 3;
$data['main_content'] = 'product_view';
//print_r($data['products']);
$this->load->view('includes/template', $data);
}
This is the get function in the products_model file
function get($id)
{
$results = $this->db->get_where('products', array('id' => $id))->result();
//get the first item
$result = $results[0];
return $result;
}
The products table contains fields such as name, price etc. Please can you tell me how to output variables from $data['product'] after it is passed into the view? I have tried so many things but nothing is working, even though the print_r (commented out) shows the data - it is not being passed into the view. I thought it may have been because the view calls a template file which references the main_content variable:
Template file contents:
<?php $this->load->view('includes/header'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer'); ?>
but i tried creating a flat view file and still couldn't access the variables.
Many thanks,
your $data array is "ripped" into single variables within the view.
print $product;
print $product_no;
print $main_content;
Handling headers & footers this way sucks and get's unmanageable pretty quickly.
Try using my Template library, your data will be passed through to the product_view no problem.

Resources