Archive for 'CodeIgniter'

CodeIgniter Error CSS Classes

When version 1.7 of CodeIgniter was released, they introduced a new form validation class that vastly simplified things. I particularly liked the new way in which any errors that occurred during form validation were displayed on screen.
Where as before, an error message for a field was displayed as follows:

<?=$this->validation->myfield_error?>

It seemed much neater with the new validation class:

<?=form_error('myfield');?>

What I found however, was there was no simple way to style a particular field if it it had an error. I wanted a similar method to displaying the error message but which would output the error css class name, if there was an error with the field.
After poking around the new validation code, I discovered that creating such a function would require the extension of two of the base files – the helper form_helper.php would be the place to put the function that I could call from the view and the library form_validation.php would be the place where I could put a function that checks whether a particular field is valid or not.
CodeIgniter provides a way to extend these files easily by placing a file of the same name with the prefix ‘MY_’ inside the appropriate folder in the application directory. So, to create the functionality I wanted, I created a MY_form_helper.php and put the following code into it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('error_class'))
{
	function error_class($field = '')
	{
		if (FALSE === ($OBJ =& _get_validation_object()))
		{
			return '';
		}
 
		return $OBJ->errorclass($field);
	}
}
?>

Then I created a MY_Form_Validation.php file and placed the following in it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class MY_Form_validation extends CI_Form_validation {
 
	function errorclass($field = '') {
		if ( !isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '')
		{
			return '';
		} else {
			return ' invalid';
		}
	}
}
?>

With these two changes, I was then able to set the classes of my field as follows:

<input type="text" name="myfield"  value="<?=set_value('myfield');?>" class="<?=error_class('myfield');?>" />

This kept the method in line with the set_value and the form_error functions and set the class to ‘invalid’ when an error occurred.

Creating PDF Documents in PHP Using Tcpdf

When developing websites, it is not going to be too long before you are required to generate a pdf for users to download. One usually searches for a suitable library for this and in php, there are a few options out there. My personal favourite, and one that is still receiving regular updates and improvements, is tcpdf.

There always seems to be a trade-off between flexibility and ease of use with these libraries and tcpdf seems to lean more towards the flexibility side of things. I prefer this, as there would be nothing worse that committing oneself to a particular library, only to find that it is not possible to generate a particulr report further down the track. On top of this, the library is available in PHP4 and PHP5 versions and is open source, should one need to tweak it any way.

Installation is pretty straight forward for and there are suitable instructions telling you how. In my case, however, I am using the CodeIgniter framework and needed to take some additional steps in order to use it. If anyone else is also using CodeIgniter, here is how I do it:

  1. Unpack the tcpdf installation package into your  system/plugins folder. This will give you a tcpdf directory in the plugins directory.
  2. Create a tcpdf_pi.php file inside the plugins directory. Place the following code in it:
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
 
// Extend the TCPDF class to create custom Header and Footer
class OnemoretakePDF extends TCPDF {
}
 
function tcpdf(){
    return new OnemoretakePDF (PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);
}
 
?>

Here, we basically instantiate tcpdf and pass in a few of the default values. You may be wondering why I have extended the TCPDF class and have not just instantiated it directly. Well, I shall come to that later.

To use this in CodeIgniter, you load the plugin and then create an instance of  it as follows:

1
2
$this->load->plugin( 'tcpdf' );
$pdf = tcpdf();

The next step really, is to visit the documentation for tcpdf. It is not the easiest to follow set of documentation there is, as it has been generated directly from the code, although there are several examples that you can pull apart to learn more. The premise here is to create a new pdf page and plot what you want on that page. This can be done directly with commands like Text() and Line() which use coordinates directly or you can also use Cell() and MultiCell() which allow you to draw using a cell system like a table and utilise borders and alignment appropriately. For those who just cannot get their heads around plotting on a page, there are commands to plot HTML, although support for styles is limited, so don’t expect to recreate a fancy webpage layout by throwing the html at it. I found that with a little bit of lateral thinking, most jobs can be done without the HTML methods anyhow.

What took me a little time to get used to, is that the coordinate system is not in pixels but by default, in millimetres. This actually makes a lot of sense, as we are creating for print here, not screen. This makes it very awkward if you are working off a design done in photoshop or similar and want to get the dimensions just right. However, a trick I soon learned was to print that image directly to a pdf and then you can use the measurement tools in your pdf reader (Foxit reader has such a tool) to measure the correct distance in millimetres.

The API for tcpdf is extensive and with it, one can achieve most tasks. One thing to note, however is that to create a standard header and footer for your document, you need to override the default header and footer methods in the main tcpdf class. This is why, in the code above, I extended the tcpdf class. It will give us the opportunity to override these methods as follows:

1
2
3
4
5
6
7
8
9
10
11
class OnemoretakePDF extends TCPDF {
    //Page header
    public function Header() {
        //header plotting code here
    }
 
    // Page footer
    public function Footer() {
      //footer plotting code here
    }
}

My biggest gripe about this library is that the documentation does not give enough detail. Coupled with that, the forum is a SourceForge forum, which frankly I find very difficult to find anything in. It would be great if there was a way to get more detail, perhaps a wiki would benefit the project a great deal – I am sure there is a lot of detailed knowledge out there about the ins and outs of the library, its just that there is no way to tap into it.

You can’t complain too much however, this project provides a very powerful pdf creation library. I have had experience with Microsoft.Net libraries of a similar nature and you can end up paying quite a lot for them. Not to mention they tend be way more restricted as to what is possible.