jigniter™

jQuery & CodeIgniter – Perfect combination for web application

A straightforward way to translate your language files in CodeIgniter

sin comentarios

Months ago we discussed about different alternatives to add i18n support to CodeIgniter applications. On this opportunity we will show how easy is to maintain your language files using CodeIgniter Language File Translator by MrKirkland and Owen Christian.

Basically what you need to do is download the zip here and then unpack the files under appropriate location, as explained in the article.

Afterward, create your desired language files languages folder. For example, if you would like to use English and Spanish, let’s say you create these two files:

  • application/languages/spanish/general_lang.php
  • application/languages/english/general_lang.php

You’d need to load that general language file in your controller or the autoload.php config file, and then choose which of these files you will use as Master file. That means the file that you will keep updated every time and use as reference when synchronizing with the other slaves files.

Then, you’ll need to run the new controller that was unpacked by pointing your browser to index.php/translator

You will be guided through the translator interface that will take care of your language strings under master and slave files. So, go to your slave files and translate each value.

In case any key in your slave file is not present under your master file, then you will see a mismatch error message warning about that behavior.

For non-english speakers: If you plan to use a different Master file rather than English, you can. In theory you’d need to edit the config file under /application/config/translator.php , but my last attempt did not work in version 0.5.1, For example, if I’d like to use Spanish as Master language instead of English, then I needed to edit the variable used in controllers/translator.php under line #87:


var $masterLang = 'spanish';

For more information, we strongly recommend to read the author’s article.

Written by admin

2010-01-12 at 7:22 pm

CodeIgniter in Spanish Language

sin comentarios

CodeIgniter has been translated to many international languages, not only the User Guide but also the messages and errors strings in its language packs.

For example, you can find Spanish translations for your CodeIgniter applications, here. [Make sure to download the right version, ie: 1.7.2]

The next step once you unpack the .zip is to copy the files into your language directory that usually is located under /system/languages so it will read /system/languages/spanish

Then, to use Spanish messages in your applications you’ll need to chaneg the default language setting in /application/config/config.php under line $config['language']

Written by admin

2010-01-11 at 1:14 pm

Publicado en Snippets Ideas

Tags: , ,

Get Location Information based on an address, city or country name

sin comentarios

In our last post we explained how to use GeoIP easily in CodeIgniter. Now we are interested in getting location information from a particular address using a Geocoder tool. For that reason, we’d recommend to take a look over How to use Google Maps API with PHP from Zimuel’s blog.

Zimuel exposes the following scenario:

Scenario: you have to check the validity of the geo data of a list of customers stored into a database. Using the Google Maps API you can easly compare the data stored into your database with the google data and fix the errors.

Moreover, his solution using Google Maps API proposes the following solution.

A PHP class that uses the Google Maps API to provide geographic information from a generic address (city, country, street+city, country. etc.).

So, based on that basis we would be interested in integrating this solution into CodeIgniter application. In order to do that, we can achieve the following steps:

1. Downloading the GMaps library from Zimuel’s blog.

2. Unpacking the zip and copy the GMaps.php file into your library directory: /application/libraries/GMaps.php

3. Put the content under example.php into your controller class where you are interested in using the Google Maps library. For example, you can use the following code to get information from a location assuming that $gmaps_key is your Google Maps key (get it from here for free), and $search is the variable containing the search string (ie: an address, a city, etc.:


        $this->load->library('GMaps', $gmaps_key );
        if ($this->gmaps->getInfoLocation( $search )) {

            echo 'Address: '.$this->gmaps->getAddress().'';
            echo 'Country name: '.$this->gmaps->getCountryName().'';
            echo 'Country name code: '.$this->gmaps->getCountryNameCode().'';
            echo 'Administrative area name: '.$this->gmaps->getAdministrativeAreaName().'';
            echo 'Postal code: '.$this->gmaps->getPostalCode().'';
            echo 'Latitude: '.$this->gmaps->getLatitude().'';
            echo 'Longitude: '.$this->gmaps->getLongitude().'';

            $this->data['lat'] = $this->gmaps->getLatitude();
            $this->data['lng'] = $this->gmaps->getLongitude();

        } else {
            echo "The response of Google Maps is empty";
        }

Finally, the text displayed in the page contains geo information such as latitude, longitude, postal code, country code and name, etc.

Written by admin

2010-01-10 at 3:48 pm

Publicado en Snippets Ideas

Tags: ,

Using GeoIP in CodeIgniter application

un comentario

The company called Maxmind published free resources to use Geo localized IP services in your web applications. I remember this service is there from long time ago.

Now, we are interested in getting geo information from users in a website, so it could be a good idea to integrate GeoIP services as a CodeIgniter plugin.

@Burak posted a short but nice article at phpandstuff.com explaining how to integrate GeoIP in a PHP script.

So, based on that article, I’d integrate the GeoIP as a plugin, by following these steps:

1. Create a new plugin file under application/plugins/geo_ip.php and I put there the content that is inside geoip.inc

2. We’d need to copy the GeoIP.dat file to any location inside our application. I used resources/geo/GeoIP.dat as location.

3. Then we’d need to load the plugin file, we can do that on any particular controller file (on demand) or we can add it as autoloaded plugin in application/config/autoload.php

4. I went to the controller class where I want to use GeoIP to grab the user’s country name and code, and put this snippet:


        $gi = geoip_open('resources/geo/GeoIP.dat',GEOIP_STANDARD);
        $country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
        $this->data['country_code'] = $country_code;
        $this->data['country_name'] = $country_name;
        $country_name = geoip_country_name_by_addr($gi, $_SERVER['REMOTE_ADDR']);
        // close the database
        geoip_close($gi);

That’s all, assuming that finally you will have the Country Code and Country Name under $this->data variable. You can see more info about why I use this way to pass information to view, under Using a Super Controller Class in CodeIgniter.

Written by admin

2010-01-09 at 9:07 am

How do I display result or error messages in CodeIgniter application

3 comentarios

Sometimes we need to display general messages or error messages to the user noticing about certain action, for example on success or failure.

Imagine you are submitting a form and then creating or updating the data in the database. You may be interested in noticing the user about the result for that action.

This is the way I use to display general messages (and error messages) in CodeIgniter application.

The result

This is how my message looks.

codeigniter-display-message

How to display the message?

Now, in order to display that information message, I do the following:

First, when submitting the form, after validating it, in the controller I call the model function that will save the entity (license in this case). I make sure that model function returns a result, and FALSE result in case of error (I usually return an array result on success with an ID element with the last inserted identifier if the result was an insert, or the just updated entity identifier if it was an update, but that is out of this article’s scope).

Controller

Imagine we are calling the following method in the controller:

$result = $this->license_model->create_or_update_license($agent_id, $state, $data);

Then, we need to see if that was an error or not. Based on that result, I will use CodeIgniter’s set_flashdata function in the Session library, as follows:

if ($result)
{
	$this->session->set_flashdata( 'message', array( 'title' => 'License created', 'content' => 'License has been saved sucessfully', 'type' => 'message' ));
	redirect('agent/licenses');	

} else
{
	$this->session->set_flashdata( 'message', array( 'title' => 'License error', 'content' => 'License could not be saved', 'type' => 'error' ));
	redirect('agent/licenses');
}

Once the Flash message has been set, I redirect the user to the form or a list of results. That is needed in order to get the flash working (you cannot just load the view in this case… well, you can but this method will not work in such case). When comparing $result TRUE or FALSE, please notice the different value for type. I am using type=message for successful messages, and type=error for error mesages.

View

In the view, just above the form, I use this snippet.



<?= @flash_message() ?>

To keep it simple, I just added @ to avoid any error message, but probably if you are looking for a better coding practice and you may not do that.

A Helper

Then, I put this flash message function as a helper function, so it is available when calling from the view.


function flash_message()
{
	// get flash message from CI instance
	$ci =& get_instance();
	$flashmsg = $ci->session->flashdata('message');

	$html = '';
	if (is_array($flashmsg))
	{
		$html = '<div id="flashmessage" class="'.$flashmsg[type].'">
			<img style="float: right; cursor: pointer" id="closemessage" src="'.base_url().'images/cross.png" />
			<strong>'.$flashmsg['title'].'</strong>
			<p>'.$flashmsg['content'].'</p>
			</div>';
	}
	return $html;
}

jQuery part

Finally, I added a simple effect to slide down and blink the message box, and adding the close functionality with a simple jQuery function. You can do something like this. Of course, you can modify it or just avoid using the jQuery effect if it is desired.


// first slide down and blink the message box
$("#flashmessage").animate({top: "0px"}, 1000 ).show('fast').fadeIn(200).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);

Some CSS styling

Finally, just add some CSS styling for #flashmessage, using message or error class names.


.message{
    border:1px solid #CCCCCC;
    width:300px;
    border:1px solid #c93;
    background:#ffc;
    padding:5px;
    color: #333333;
    margin-bottom:10px;
}

Enjoy it.

Written by admin

2009-09-18 at 11:49 pm

Publicado en Tutorials

Tags: , , ,

CodeIgniter 1.7.2 released

sin comentarios

The new CodeIgniter 1.7.2 release includes the following general changes:

  • Compatibility for PHP 5.3.0
  • The Form Helper class has been improved
  • New simple Cart Class has been introduced (we commented something about it in an earlier post)
  • A new function is_php() has been introduced
  • Also, show_error() function allows to send HTTP responses.

This new release can be downloaded from here.

Written by admin

2009-09-17 at 11:15 am

Publicado en Uncategorized

Fast way to randomly choose an Array item

sin comentarios

When dealing with arrays in PHP, I usually need to choose a random item to display, for example an image that rotates randomly in a homepage or interior page, actually doesn’t matter which page.

The applications and needs may differ a lot, but here is a simple snippet that you can use to randomly select an item in a PHP Array.

Basically it uses array_rand() function.

For example, imagine we have the filenames for images that we want to rotate in a page (banners or whatever). Then I’ll define an array, and then I will use array_rand() to get a random key.


$headers = array("menu_header_1.jpg", "menu_header_2.jpg", "menu_header_3.jpg", "menu_header_4.jpg");
$value = $headers[array_rand($headers)];

Written by admin

2009-09-04 at 11:41 am

Publicado en Snippets Ideas

Tags: ,

Get a single table field value from database using CodeIgniter

sin comentarios

If you want to get a single value from a database table, then an easy way to achieve that in CodeIgniter could be:


$count = $this->db->query('SELECT count(*) as count FROM departments')->row()->count;

Replace department by your table name, and of course, replace count(*) as count by your desired field.

Written by admin

2009-08-30 at 10:23 am

Publicado en Uncategorized

How to Backup files using CodeIgniter

sin comentarios

If you are developing a CodeIgniter application and need to backup files, let’s say in a .zip file, then you are lucky since CodeIgniter has a Zip Encoding library.

In my case, I used this library to create file backup, most of the time. But you can use it for other interesting things, for example adding string data to a .zip file and then allow users to download that file from a web page.

In this post I’ll only show the case we need to backup a directory using CodeIgniter and save the content to a .zip file.

Originally, this code read images and Flash files from the database and then save these images (binary data) into the file system. Since that action will run periodically using a Cron job, I’d like to do a backup for the existing files before overwriting. That’s where the Zip Class comes in action to compress a directory into an archive.


function _create_backup()
{
	$this->load->library('zip');
	$path = 'media/';
	$this->zip->read_dir($path);
	$result = $this->zip->archive('my_backup.zip');
	return $result;
}

If you want the zip file to have a better name, probably you can add the current date as  a suffix, so you can know where the file was created. To do that, you can replace ‘my_backup.zip’ by:


$result = $this->zip->archive('media_backup_'.date('Ymdhs').'.zip');

That will add the current date as a suffix.

Hope this snippet helps you the next time you need to backup files. If you are interested in other usages, you can refer to the CodeIgniter’s  User Guide for more information.

Written by admin

2009-08-29 at 11:30 pm

How do I use Constants in CodeIgniter applications?

sin comentarios

Usually I need to use constants or pass them as parameter in a function.

I don’t like the idea to hardcode these values in the code, nor sometimes I don’t like to use the PHP define() function to define constants since later it is a mass to search where a constant for a given entity has been defined.

Recently I started to use constants by defining these constants in a model Class (as reference you can find more info about Object Constants here).

Let’s say we have an Order_model class that manages Orders in an e-commerce application built in CodeIgniter. That Order_model class will implement the methods for create, update, list or view orders, for example.

Now, imagine we want to define simple states for each order. So, an order can be APPROVED as 1 or PENDING as 0.

A natural way to do that (wrong way IMHO) is to set the numeric value (1 or 0 in this case) hardcoded.

Instead of that, I created two object constants, as follows:


class Order_model extends Model {

    var $tablename = 'Orders';
    var $tablename_details = 'OrderDetails';

    const ORDER_STATUS_PENDING = 0;
    const ORDER_STATUS_APPROVED = 1;

Then, imagine we have an update_order_status() function in that model that will change the order status:


function update_order_status($order_id, $new_status)

Later, in the Controller class that will call this update function, I’ll use the constant in this way:


$this->order_model->update_order_status($order_id, Order_Model::ORDER_STATUS_APPROVED);

By doing that, the next time I need to change or maintain that code, I’ll go directly to the model class.

Written by admin

2009-08-28 at 5:19 pm

Publicado en Snippets Ideas

Tags: ,

Unit Testing in CodeIgniter (Who use it?)

sin comentarios

Using Unit tests is a best practice when developing software.

CodeIgniter has a Unit Testing class that is aimed to provide support for Unit Tests in your code.

Despite the CI Class for Unit Testing is quite simple, it may be very helpful to determine if what you are coding is exactly what you expect or not, by doing simple test cases.

I’d suggest to review their Unit Testing class.

The initialization of this library is quite simple simple, too. You just need to add the following line, and then the Unit Test object will be available using $this->unit.


$this->load->library('unit_test');

Once you loaded the library, you can start running simple tests. For each test, you specify the $test parameter (ie: 1+1), the expected result and the test name.

Also you can specify if a value is any of the available data types supported in the application, ie: is_string, is_bool, is_false, is_float, and so on, to evaluate if the result match with the expected data type.

Written by admin

2009-08-28 at 9:35 am

Simple Shopping Cart in CodeIgniter

3 comentarios

cart-codeigniterExpressionEngine Dev Team is preparing a Cart library for CodeIgniter version 1.7.2

If you are interested in a preview of this CodeIgniter shopping cart, you can download the Cart.php from trunk, or you can wait until 1.7.2 is launched.


http://dev.ellislab.com/svn/CodeIgniter/trunk/system/libraries/Cart.php

The documentation is here:

http://dev.ellislab.com/svn/CodeIgniter/trunk/user_guide/libraries/cart.html

Things you can do with this Cart library

Add items to the cart. You use an array specifying id, quantity, price, name and a sub-array with options.

Add multiple items to the cart, at once. Similar to adding a single product but in this case you can specify an array of products.

Display the cart content. For this purpose, you will create a view file and use the Cart functions to retrieve the cart content, options and calculate totals.

Update the cart. For example, updates the quantity for an existing item insider your cart.

More inside this Cart

Then, you can other accessible functions that you can use, for example:

  • Calculate the Total amount in the cart.
  • Count the number of items in the cart.
  • Return an array containing everything inside the cart.
  • Return the options assigned for a particular product.
  • Destroy the cart.

Written by admin

2009-08-21 at 8:37 pm

Publicado en Snippets Ideas

Tags: ,

Solution to: My Cookies are not working in CI application

sin comentarios

I have been experimenting this problem before, and let me ask you the following question… are you using Xampp? I have experimenting this problem in Xampp only.

If yes, then you can try the following solutions. (Although you can try the solutions whatever is your server).

Read more »

Written by admin

2009-08-21 at 7:42 pm

Publicado en Troubleshooting

Tags:

Using a super Controller class in CodeIgniter

4 comentarios

CodeIgniter is easy to understand if you know how MVC design pattern works. Just need to define your model, your controller and your views.

However, sometimes you need to reuse code in all your site pages and probably you ask yourself “How do I do that?”.

Well, here is a simple tip that may help you to reuse generic data, fields, etc. in your CodeIgniter application.

Read more »

Written by admin

2009-08-15 at 3:34 pm

Publicado en Uncategorized

Use your Site URL or Base URL in Javascript functions

4 comentarios

When writing AJAX applications with CodeIgniter, you usually want to post to a controller class by using Javascript functions. For example, if you are using jQuery for posting a form or loading back a page using an AJAX style, then you need to call the Controller class from your jQuery code.

Read more »

Written by admin

2009-08-14 at 9:50 pm

Publicado en Snippets Ideas

Profiling your CodeIgniter applications

sin comentarios

The CI Output Class has enable_profiler() to set enable the profiler in CodeIgniter.

By using this operation, you can enable or disable the profiler in the output.


$this->output->enable_profiler(TRUE);

The profiler is very useful for debugging purposes, you can see a footer with information all the time while running your application in development phase.

Read more »

Written by admin

2009-08-14 at 10:47 am

CodeIgniter and SEO

sin comentarios

One of the powerful features of CodeIgniter is its great support for SEO purposes.

Titles, friendly URL are just an example of what you can do with CodeIgniter.

I’d recommend this excellent article from SEO Coding, explaining some CodeIgniter tips for SEO.

In addition, if you are optimizing your application for search engines, then you may be interested in removing index.php from the default installation of CodeIgniter application. You can do that by reading this article.

You also may be interested in reading this forum thread, explaining that controllers do not support dashes, so take that in mind when writing your own controllers in CodeIgniter. However, you can use custom Routes for routing URL friendly controller names to your existing controllers.

At URL Helper, you may find a great helper function for preparing titles for URLs, that’s good to optimize your titles for Search Engine Optimization.


$title = "My SEO title";
$url_title = url_title($title);

will produce this: My-SEO-title


$title = "My SEO title";
$url_title = url_title($title, 'underscore', TRUE);

will produce a different title using underscore and lowercase, like this: my_seo_title

Written by admin

2009-08-12 at 2:48 pm

Publicado en Snippets Ideas

Tags: ,

Simple Form Generation in CodeIgniter

7 comentarios

If you are using CodeIgniter, as well as any other PHP framework, you may notice that building CRUD forms is one of the most bother and routine tasks. Probably 80% of general web applications uses CRUD (create/read/update/delete).

In CodeIgniter, you can use any of the form generation libraries.

One of my preferred libraries is Form Generation Library by Frank Michel (see @macigniter’s thread here). It allows you to create clean XHTML forms with CodeIgniter. See demo here.

Using Form Generation Library

So, in order to use this library, you need to download it from here (library files only is enough if you don’t want the entire site structure).

Read more »

Written by admin

2009-08-02 at 6:30 pm

Publicado en Tutorials

Tags: , ,

Debug CodeIgniter AJAX applications with FireIgnition

sin comentarios

image

If you are building rich AJAX applications with CodeIgniter, you may encounter that traditional debug utilities may not be suitable for debugging tasks that involve AJAX function calls.

Firebug addon with its FirePHP plugin can enhance your debugging process.

Read more »

Written by admin

2009-07-26 at 9:48 am

Publicado en Tutorials

Tags:

Remove index.php from URL

9 comentarios

CodeIgniter is designed to be search-engine and human friendly. By default, index.php will be included in the URLs, but it can be easily removed using .htaccess file with some rules.

Read more »

Written by admin

2009-07-25 at 2:28 pm

Publicado en Tutorials

Tags: