Wednesday, January 29, 2014

Assigning Multiple Classes For Click Event Using jQuery

I have an click event that I want to assign to more than one class. The reason for this is that I'm using this event on different places in my application, and the buttons you click have different styling in the different places.

I have used following method and it worked for me. You can select multiple classes at once with jQuery like this:
$(".class1, .class2").click(function(){
   alert("clicked");    
});​
Fiddle: http://jsfiddle.net/Afg5s/1/

In this way you can assign more than one class for any event using jQuery.

Source: http://stackoverflow.com/a/10511922

Tuesday, January 28, 2014

How to Add Multiple Languages Support in CodeIgniter ?

CodeIgniter comes with multi-language support, also known as internationalization which enables us to dynamically present our application’s interface in different languages without duplicating the existing source code for each language.

Configuring Multi-Language Support
First we need to configure the necessary files before we can start using language support. The CodeIgniter config file, located in the application/config directory, contains an option called language which defines the default language of the application.
<?php
$config['language'] = 'english';

CodeIgniter allows you to drop in as many languages as you want in the ../application/language/ folder. For example, if I wanted to add support for Swedish, I would create a folder inside language called "swedish". All language files must end in _lang. Let’s create some language files that contain error messages for a sample application. Create the file english/message_lang.php (it’s important that all of the language files have the suffix _lang.php). The following code contains some sample entries for the content of our language file.

Also keep in mind that for every key must be present in all of your language files. So if your ../language/english/message_lang.php file looks like this:
<?php
$lang["msg_first_name"] = "First Name";
$lang["msg_last_name"] = "Last Name";
$lang["msg_dob"] = "Date of Birth";
$lang["msg_address"] = "Address";
// more keys...
Then your ../language/swedish/message_lang.php file must look something like this:
<?php
$lang["msg_first_name"] = "Förnamn";
$lang["msg_last_name"] = "Efternamn";
$lang["msg_dob"] = "Födelsedatum";
$lang["msg_address"] = "adress";
// more keys...
Note that order does not matter in the language files. All keys are part of a larger array.

Of course, you can have multiple language files inside a single language directory. It’s recommended to group your messages into different files based on their context and purpose, and prefix your message keys with a file-specific keyword for consistency.

Loading the Language Files
There are two ways to load a language files in Codeigniter. Applying hook is the best alternative to add multi languages support.
1. Only Controller
2. Using Hook

1. Only Controller
Even though we create language files, they are not effective until we load them inside controllers. The following code shows how we can load the files inside a controller:
<?php
class TestLanguage extends CI_Controller
{
    public function __construct() {
        parent::__construct();       
        $this->lang->load("message","english");
        // or ($this->lang->load("message","swedish");)
    }
 
    function index() {
        $data["language_msg"] = $this->lang->line("msg_first_name");
        $this->load->view('language_view', $data);
    }
}

Here we’ve used a controller’s constructor to load the language file so it can be used throughout the whole class, then we reference it in the class’ index() method.

The first parameter to the lang->load() method will be the language’s filename without the _lang suffix. The second parameter, which is optional, is the language directory. It will point to default language in your config if it’s not provided here.

We can directly reference the entries of a language file using the lang->line() method and assign it’s return to the data passed into the view templates. Inside the view, we can then use the above language message as $language_msg.

<?php
$this->lang->line("language_msg");
There may be an occasion when we need to load language files directly from the views as well. For example, using language items for form labels might be considered a good reason for directly loading and accessing messages inside views. It’s possible to use the same access method for these files inside views as inside controllers.
<?php
lang("language_msg");
2. Using Hooks
Luckily, we can use CodeIgniter hooks to build a quick and effective solution for loading language files automatically for each controller. CodeIgniter calls a few built-in hooks as part of its execution process. We’ll use the post_controller_constructor hook which is called immediately after our controller is instantiated and prior to any other method calls.

We enable hooks in our application by setting the enable_hooks parameter in the main config file.
<?php
$config['enable_hooks'] = TRUE;
Then we can open the hooks.php file inside the config directory and create a custom hook as shown in the following code:
<?php
$hook['post_controller_constructor'] = array(
    'class' => 'LanguageLoader',
    'function' => 'initialize',
    'filename' => 'LanguageLoader.php',
    'filepath' => 'hooks'
);
This defines the hook and provides the necessary information to execute it. The actual implementation will be created in a custom class inside the application/hooks directory. This hooks class will load the language dynamically from the session.
<?php
class LanguageLoader
{
    function initialize() {
        $ci =& get_instance();
        $ci->load->helper('language');
 
        $site_lang = $ci->session->userdata('site_lang');

/* If you want to use cookie instead of session 
$site_lang = $ci->input->cookie('site_lang'); */

        if ($site_lang) {
            $ci->lang->load('message',$ci->session->userdata('site_lang'));
        } else {
            $ci->lang->load('message','english');
        }
    }
}

Inside the LanguageLoader class we get the active language and load the necessary language files, or we load the default language if the session key is absent. We can load multiple language files of a single language inside this class.

Switching Between Different Languages
Once we have established support for multiple languages, a link for each language can be provided to the user, generally in one of our application’s menus, which the users can click and switch the language. A session or cookie value can be used to keep track of the active language.

Let’s see how we can manage language switching using the hooks class we generated earlier. First we need to create a class to switch the language; we’ll be using a separate controller for this as shown below:
<?php
class LangSwitch extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }
 
    function switchLanguage($language = "") {
        $language = ($language != "") ? $language : "english";
        $this->session->set_userdata('site_lang', $language);
        redirect(base_url());
    }
}
Then we need to define links to switch each of the available languages.
<a href='<?php echo $base_url; ?>langswitch/switchLanguage/english'>English</a>
<a href='<?php echo $base_url; ?>langswitch/switchLanguage/swedish'>Swedish</a>
Whenever the user chooses a specific language, the switchLanguage() method of the LangSwitch class will assign the selected languages to the session and redirect the user to the home page. Now the active language will be changed in the session and will load the specific language file for the active language.

Source: http://www.sitepoint.com/multi-language-support-in-codeigniter/

Friday, January 24, 2014

Swedish Language Form Validation Support For CodeIgniter 2.1.x

I have translated the form validation into Swedish Language of CodeIgniter Version 2.1.X. This will be useful when you are adding multi-languages support in Codeigniter 2.1.x. This will help you to show form validation rules in Swedish Language.

Just add following form_validation_lang.php under application/language/swedish folder.
<?php

$lang['required']   = "%s är obligatoriskt.";
$lang['isset']    = "%s måste innehålla ett värde.";
$lang['valid_email']          = "%s måste innehålla en giltig e-post.";
$lang['valid_emails']          = "%s måste innehålla all giltig e-poster.";
$lang['valid_url']   = "%s måste innehålla en giltig URL.";
$lang['valid_ip']   = "%s måste innehålla en giltig IP.";
$lang['min_length']   = "%s måste innehålla minst %s tecken.";
$lang['max_length']   = "%s får inte vara längre än %s tecken.";
$lang['exact_length']          = "%s måste vara exakt %s tecken.";
$lang['alpha']    = "%s får bara innehålla bokstäver.";
$lang['alpha_numeric']          = "%s får bara innehålla alfanumeriska tecken.";
$lang['alpha_dash']          = "%s får bara innehålla alfanumeriska tecken, understreck och bindestreck.";
$lang['numeric']   = "%s måste innehålla ett nummer.";
$lang['is_numeric']   = "%s får bara innehålla numeric tecken.";
$lang['integer']   = "%s måste innehålla ett integer.";
$lang['regex_match']          = "%s är inte i rätt format.";
$lang['matches']   = "%s skiljer sig från %s.";
$lang['is_unique']    = "%s måste innehålla ett unikt värde.";
$lang['is_natural']   = "%s får bara innehålla positiva nummer.";
$lang['is_natural_no_zero']         = "%s måste innehålla ett nummer större än noll.";
$lang['decimal']   = "%s måste innehålla ett decimal nummer.";
$lang['less_than']   = "%s måste innehålla ett nummer mindre än %s.";
$lang['greater_than']          = "%s måste innehålla ett nummer större än %s.";


/* End of file form_validation_lang.php */
/* Location: ./application/language/swedish/form_validation_lang.php */

Thursday, January 23, 2014

How To Upload Multiple files Using CodeIgniter ?

This is just an extension to the existing Codeigniter's Upload class to take advantage of multiple uploads in one form field.

Installation Copy MY_Upload.php to your application/libraries directory. If you are using a prefix other than MY_ for your classes and/or alternative file paths, adjust accordingly.

Usage Load the Upload class as usual, in your controller call the function do_multi_upload(). If you are uploading a single file, it'll default to the regular do_upload() method. In the form, set field names to array (e.g. name="userfile[]")

MY_Upload.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Exenstion File Uploading Class
 */
  
class MY_Upload extends CI_Upload {
 
 public function do_multi_upload( $field = 'userfile', $return_info = TRUE, $filenames = NULL ){

  // Is $_FILES[$field] set? If not, no reason to continue.
  if ( ! isset($_FILES[$field]))
  {   
   $this->set_error('upload_no_file_selected');
   return FALSE;   
  }
  
  //If not every file filled was used, clear the empties
  
  foreach( $_FILES[$field]['name'] as $k => $n )
  { 
   if( empty( $n ) )
   {
   
    foreach( $_FILES[$field] as $kk => $f )
    {    
     unset( $_FILES[$field][$kk][$k] );     
    }        
   }   
  }
  
  // Is the upload path valid?
  if ( ! $this->validate_upload_path($field) )
  {

   // errors will already be set by validate_upload_path() so just return FALSE
   return FALSE;
  }

  //Multiple file upload
  if( is_array( $_FILES[$field] ) )
  { 
   //$count = count($_FILES[$field]['name']); //Number of files to process
   
   foreach( $_FILES[$field]['name'] as $k => $file )
   {    
    // Was the file able to be uploaded? If not, determine the reason why.
    if ( ! is_uploaded_file($_FILES[$field]['tmp_name'][$k] ) )
    {     
     $error = ( ! isset($_FILES[$field]['error'][$k])) ? 4 : $_FILES[$field]['error'][$k];
     
     switch($error)
     {
      case 1: // UPLOAD_ERR_INI_SIZE
       $this->set_error('upload_file_exceeds_limit');
       break;
      case 2: // UPLOAD_ERR_FORM_SIZE
       $this->set_error('upload_file_exceeds_form_limit');
       break;
      case 3: // UPLOAD_ERR_PARTIAL
       $this->set_error('upload_file_partial');
       break;
      case 4: // UPLOAD_ERR_NO_FILE
       $this->set_error('upload_no_file_selected');
       break;
      case 6: // UPLOAD_ERR_NO_TMP_DIR
       $this->set_error('upload_no_temp_directory');
       break;
      case 7: // UPLOAD_ERR_CANT_WRITE
       $this->set_error('upload_unable_to_write_file');
       break;
      case 8: // UPLOAD_ERR_EXTENSION
       $this->set_error('upload_stopped_by_extension');
       break;
      default :   $this->set_error('upload_no_file_selected');
       break;
     }
  
     return FALSE;
    }
        
    // Set the uploaded data as class variables
    $this->file_temp = $_FILES[$field]['tmp_name'][$k];
    $this->file_size = $_FILES[$field]['size'][$k];
    $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type'][$k]);
    $this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
    
    if(empty($filenames))
    {
     $this->file_name = $this->_prep_filename($_FILES[$field]['name'][$k]);     
    }
    else
    {
     $this->file_name = $this->_prep_filename($filenames[$k]);
    }
    
    $this->file_ext  = $this->get_extension($this->file_name);
    $this->client_name = $this->file_name;
    
    // Is the file type allowed to be uploaded?
    if ( ! $this->is_allowed_filetype())
    {
     $this->set_error('upload_invalid_filetype');
     return FALSE;
    }
    
    // if we're overriding, let's now make sure the new name and type is allowed
    if ($this->_file_name_override != '')
    {
     $this->file_name = $this->_prep_filename($this->_file_name_override);
  
     // If no extension was provided in the file_name config item, use the uploaded one
     if (strpos($this->_file_name_override, '.') === FALSE)
     {
      $this->file_name .= $this->file_ext;
     }
  
     // An extension was provided, lets have it!
     else
     {
      $this->file_ext  = $this->get_extension($this->_file_name_override);
     }
  
     if ( ! $this->is_allowed_filetype(TRUE))
     {
      $this->set_error('upload_invalid_filetype');
      return FALSE;
     }
    }
 
    // Convert the file size to kilobytes
    if ($this->file_size > 0)
    {
     $this->file_size = round($this->file_size/1024, 2);
    }
  
    // Is the file size within the allowed maximum?
    if ( ! $this->is_allowed_filesize())
    {
     $this->set_error('upload_invalid_filesize');
     return FALSE;
    }
  
    // Are the image dimensions within the allowed size?
    // Note: This can fail if the server has an open_basdir restriction.
    if ( ! $this->is_allowed_dimensions())
    {
     $this->set_error('upload_invalid_dimensions');
     return FALSE;
    }
 
    // Sanitize the file name for security
    $this->file_name = $this->clean_file_name($this->file_name);
  
    // Truncate the file name if it's too long
    if ($this->max_filename > 0)
    {
     $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
    }
  
    // Remove white spaces in the name
    if ($this->remove_spaces == TRUE)
    {
     $this->file_name = preg_replace("/\s+/", "_", $this->file_name);
    }
  
    /*
     * Validate the file name
     * This function appends an number onto the end of
     * the file if one with the same name already exists.
     * If it returns false there was a problem.
     */
    $this->orig_name = $this->file_name;
  
    if ($this->overwrite == FALSE)
    {
     $this->file_name = $this->set_filename($this->upload_path, $this->file_name);
  
     if ($this->file_name === FALSE)
     {
      return FALSE;
     }
    }
  
    /*
     * Run the file through the XSS hacking filter
     * This helps prevent malicious code from being
     * embedded within a file.  Scripts can easily
     * be disguised as images or other file types.
     */
    if ($this->xss_clean)
    {
     if ($this->do_xss_clean() === FALSE)
     {
      $this->set_error('upload_unable_to_write_file');
      return FALSE;
     }
    }
  
    /*
     * Move the file to the final destination
     * To deal with different server configurations
     * we'll attempt to use copy() first.  If that fails
     * we'll use move_uploaded_file().  One of the two should
     * reliably work in most environments
     */
    if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
    {
     if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
     {
      $this->set_error('upload_destination_error');
      return FALSE;
     }
    }
  
    /*
     * Set the finalized image dimensions
     * This sets the image width/height (assuming the
     * file was an image).  We use this information
     * in the "data" function.
     */
    $this->set_image_properties($this->upload_path.$this->file_name);
  
    
    if( $return_info === TRUE )
    {     
     $return_value[$k] = $this->data();    
    }
    else
    {    
     $return_value = TRUE;    
    }    
   }
   
   return $return_value;  
  }
  else //Single file upload, rely on native CI upload class
  {  
   $upload = self::do_upload();   
   return $upload;  
  } 
 }

}

?>
Source: https://github.com/nicdev/CodeIgniter-Multiple-File-Upload