CodeIgniter pagintation - appending the page number to "page" string - codeigniter

What I am trying to achieve is urls outputting via pagination like this:
http://www.mysite.com/users/page5
or
http://www.mysite.com/users/page-5
At present, it will be using the URI segments like this:
http://www.mysite.com/users/page/5
I can modify the routes.php config file to route the path if the first two URLs are used. So, that's not the issue.
What I am having trouble with is, how do I initialize the settings for the pagination, so that the $this->pagination->create_links() will create a pagination with items having links like in the first or the second format?
Let me know if you need more explanation or examples regarding this. I'm not much good in explaining things. :)
Thank you

This functionality already exists in the in-development version of CodeIgniter 3.0. You can view the Pagination class as it sits here.
To use this library, you can either A) use all of CI 3.0 (it's pretty stable), or B) extend (or, more realistically, replace) the Pagination library by creating application/libraries/MY_Pagination.php and filling it with the contents of the link above. (Full disclosure: it's been a while since I tinkered with CI, so I don't know if anything has changed since that may result in errors with any of this answer.)
To use the feature you want, specify your base URL minus the page-X segment, set that you want to use page numbers instead of offset in your URI segment, and then specify a prefix.
$config['base_url'] = site_url('users');
$config['use_page_numbers'] = true;
$config['prefix'] = 'page-';
Make sure to include your other obvious items as well, such as per_page, etc.

To change the functionality of the Pagination library, you can extend the library and override the create_links() function.
Create a file named MY_Pagination.php in application/libraries/
The file should have the following structure, so you can change or add additional functionality to CI's native Pagination library. (It is bad practice to directly change the Pagination library in the system directory.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Pagination extends CI_Pagination {
public function __construct()
{
parent::__construct();
}
}
You'll then need to add the create_links() function to your MY_Pagination class, allowing you to override its default functionality. Below is an explanation of what you could change to achieve your desired output (you may want to add flexibility, by adding a parameter to the function, but this is the simplest change that I could think of.)
function create_links()
{
// You can copy the exact functionality of this function from:
// system/libraries/Pagination.php
// The line you want to change is:
// $this->base_url = rtrim($this->base_url, '/') .'/';
// Changing to this: $this->base_url = rtrim($this->base_url, '/') .'';
// Will create links in this format: ../page5
// Or changing to this: $this->base_url = rtrim($this->base_url, '/') .'-';
// Will create links in this format: ../page-5
}

Related

Multilingual set up of codeigniter

I'm using this tutorial http://sumonbd.wordpress.com/2009/09/16/develop-multilingual-site-using-codeigniter-i18n-library/ for multilingual in codeigniter.
I've follow the instruction listed correctly. It does not gave me any error, but I couldn't say that it is working properly.
when I run through mysite.com/en/about and mysite.com/fr/about it always give me the default language which is english. I'm wondering if there is any configuration that I need to set to be able to work properly.
I'm thinking about this in config.php
$config['language']
and
this in autoload.php
$autoload['language']
Do I have to configure those? or any other configuration to work the multilingual properly.
After analyzing the code of CI and the codes in the blog I've come up to this solution.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class About extends CI_Controller {
function index()
{
// you might want to just autoload these two helpers
$this->load->helper('language');
$this->load->helper('url');
$this->getLang();
$this->load->view('about');
}
function getLang(){
$url = $_SERVER['REQUEST_URI'];
$lang = explode("/", $url);
if($lang[2] == 'en'){
// load language file
return $loadLang = $this->lang->load('english','english');
}
else if($lang[2] == 'fr'){
// load language file
return $loadLang = $this->lang->load('french','french');
}
else{
// load language file
return $loadLang = $this->lang->load('english','english');
}
return false;
}
}
I've created the function getLang() in which I load the language file.
$this->lang->load('language_file','language_folder');
Sorry, you don't provide enough information about what you have done. But I'll try to answer.
I've try the updated tutorial, and it's works like a charm.
First, you point to an out to date tutorial. This is the source of your link with an update: source
Second, a file prefixed with MY_ (default configuration) is a core classes ( see Core Classes ) not a library and should be placed on application/core directory.
Third, in your view file, try to avoid using php short tag (<?=$variabel;?>) because not all server configuration enable php short tag. Use normal echo tag instead <?php echo $var; ?>. Longer, but worth it as you write the standard pattern.
As I said before, if you follow the updated tutorial your script should work as mine. I hope this help. Sorry for my English, correct me if I'm wrong.
i think you should have a look at URI-Language-Identifier i use it for my multilingual projects, and its working as it should.

How do you create relative links in CodeIgniter?

Example I have the following code in Controller:
class Main extends CI_Controller {
public function index()
{
$this->load->view('main_view');
}
public function create ()
{
$this->load->view('create_view');
}
}
If I want to create a relative link to create, how do I accomplish that? The following link in view doesn't always work. What is apporpiate way to create relative links in CodeIngiter?
Create
Create
or simply:
<?= anchor('/main/create', 'Create'); ?>
Make sure you have loaded the URL Helper.
You don't have to do anything special or load any helpers, just keep in mind that paths will be relative to the url and not the filesystem or controller.
Assuming your installation is in the root directory of your domain, let's say your current URL is http://localhost/class/method/var:
Will work from anywhere
Will go to http://localhost/class/method/var/create
Will go to http://localhost/class/method/create
Relative paths are not your friend in Codeigniter, you are better off sticking with full urls (typically using the helper functions like base_url() and site_url()), or to use the forward slash (relative from root). People have mentioned using the <base> html tag, but I don't personally recommend it. You are going to have some very wacky urls if you use ../../relative paths when you get deeper into the url segments. Example:
If you are here:
http://localhost/controller/method/var1/var2/var3
A link might look like this:
Probably not what you want, but it's an option you may choose. I recommend using one of the other two.
Just to point another alternative, if you dont like the idea of writing a php fragment in each href, and if the other approaches don't satisfy you. You can use put a common <BASE > tag in your html header (for example that points to the root of your application), and then remember that every relative url in your pages will be with respect with that url.

SEO-friendly URLs in CodeIgniter without the use of slugs?

Is there a way (via routing) in CodeIgniter to change:
example.com/category/4 to example.com/category/foo-bar
where Foo Bar is the name of category 4 in the database?
Access from the SEO-friendly URL should be allowed, but access via the integer should cause a 404 error.
This should also work dynamically, where any integer is automatically converted to a URL-safe version of its corresponding category name.
I've seen a few solutions that use 'slugs'... is there a decent alternative?
Thanks.
I've only been working with CodeIgniter for the past couple of months in my spare time, so I'm still learning, but I'll take a shot at this (be gentle):
There is a url_title() function in the URL Helper (which will need loaded, of course) that will change Foo Bar to foo-bar.
$name = 'Foo Bar';
$seo_name = url_title($name, TRUE);
// Produces: foo-bar
http://codeigniter.com/user_guide/helpers/url_helper.html
The URL helper strips illegal characters and throws in the hyphens by default (underscores, by parameter) and the TRUE parameter will lowercase everything.
To solve your problem, I suppose you could either do a foreach statement in your routes.php file or pass the url_title() value to the URL, rather than the ID, and modify your code to match the url_title() value with its category name in the DB.
Afaik the link between 4 and "foo-bar" has to be stored in the DB, so you'll have to run some queries. This is usually not done via routing in CI. Also routing just points a URL to a controller and function and has little to do with url rewriting.
Why don't you want to use slugs?
You could try storing the search engine friendly route in the database using this method or this one.
I wouldn't recommend throwing a 404. Use the canonical link tag in the instead if your worried about Google indexing both http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html.
But if you really want to I guess you could write a function that is called during the pre_controller hook http://codeigniter.com/user_guide/general/hooks.html that checks to see if the URL has an integer as the second segment then call the show_404() method. Perhaps a better solution when writing this function would be to redirect to the SEO friendly version.
Is there a way (via routing) in CodeIgniter to change:
example.com/category/4 to example.com/category/foo-bar
where Foo Bar is the name of category 4 in the database?
Yes.
Using CI 3,
http://www.codeigniter.com/user_guide/general/routing.html
Use Callbacks, PHP >= 5.3
$route['products/([a-zA-Z]+)/edit/(\d+)'] = function ($product_type, $id)
{
return 'catalog/product_edit/' . strtolower($product_type) . '/' . $id;
};
You can route to call a function to extract the name of the category.
Hope I answered your question and can help more people to like codeigniter as I believe it's speedy and light.
Slugs usage is important to make web application more secure which i think is important.
A better recommendation will be to use route to give you a better solution.
$route['(:any)/method/(:num)'] = 'Class/method';
or
$route['(:any)/method/(:num)'] = 'Class/method/$1';
$route['(:any)/gallery/(:num)'] = 'Class/gallery/$1';
base_url()/business-services/gallery/6
base_url()/travel/gallery/12
how to modify routes in codeigniter
Have fun :)

Global variables in CodeIgniter view

I am following the Nettuts tutorial to implement Basecamp-style subdomains with CodeIgniter.
Based on the calling subdomain, the subdomain table in the database returns an extension corresponding to that subdomain. So say for stackoverflow.mywebsite.com, it will return the extension sf, and the image folder and CSS file used all over the website will change on the basis of this extension; for example, images_sf, style_sf.css, etc.
Now, what is the best way to fetch this extension anywhere in M, V, or C ?
Options:
Cookies
Dynamically setting CI config variable
Set a variable for this in MY_Controller and access that variable via $this-> anywhere.
Send that variable from each controller to models, helpers, views or libraries.
Did I miss any other options? Also, which one will be best assuming this will be heavily used all over the code?
Thanks
Personally, I would create a base controller for each site that you extend, and just use $this->load->vars($data); to load the information you need globally set.
In the constructor of your specific base Controller just load the data into the views globally like this.
$data->some_var = "some value";
$this->load->vars($data);
And then in all your views loaded by this controller (or base controller) you can utilize the variable $some_var directly in the view.
Your best bet is probably option 3, to put it in the constructor of your base contoller, probably MY_controller or whatever you are extending Controller (now CI_Controller with the CI2.0 official release)
However if all you're doing is getting an extension, there might not be a reason to have a database table, since you could just keep it in a config file
I'd do something like this... in MY_Controller.php (This is CI 2.0 syntax)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
$subdomain_name = $subdomain_arr[0];
$this->load->config('sub_prefix');
$pre_arr = $this->config->item('prefixes');
/* Check to make sure the subdomain name is in the config array */
$this->prefix = isset($pre_arr[$subdomain_name]) ? $pre_arr[$subdomain_name] : '';
}
Then in the config file (sub_prefix.php)
<?php if (! defined('BASEPATH')) exit('No direct script access');
$config['prefixes'] = array('subdomain1' => 'sub1',
'stackoverflow' => 'sf');
That way you don't have to run an extra query everytime the page loads for something that is relatively static...if you got to the point where there would be a lot more information you would need other than a prefix, then it would make sense to do it with the database
You can now just use $this->prefix in any of the views, controllers, or models you will be using... the best way to do it for something that is heavily use all over your application.

Page-specific logic in Joomla

I am trying to enable JavaScript in a Joomla template to behave differently depending on the page. In particular, I have set the Key Reference as that appears to be the most appropriate value I could find for this purpose. Unfortunately, I can't seem to access it in my code. I tried:
$this->params->get("keyref")
and a few other variations, but they simply returned a blank. How can I retrieve this value or is there a better way of writing page specific logic.
Related Articles
Joomla load script in a specific page: This would work, but seems like overkill for what I want to do here.
Each page can be given an alias. We can retrieve the alias using code from the forum:
function getCurrentAlias()
{
$menu = &JSite::getMenu();
$active = $menu->getActive();
return $active->alias;
}
We can then inject this into the Javascript:
var alias= '<?php echo getCurrentAlias(); ?>';
I'm not aware of keyref, but I would solve it by using the class suffix parameter you can set for each menu entry.see I would use a space in front of this suffix. With javascript you can then try to read this classname (suffix without the space) on each page.
getElementsByClassName("mysuffix");
for example
If this returns multiple objects, you know on which page you are. Will that help you?

Resources