Open Source

0 3111

jquery_bumper.sh-600x600
Today I decided to revisit how to best allow only numerics in a text field.  In the past, I have done this on the keydown event and matched against the key to see if that key that was pressed was allowed in the field.  This can then stop any unwanted keys from being allowed into the field.  Usually, it becomes a little bit of a headache because you do want to allow the user to use backspace, delete, arrows, decimal, hyphen, etc…  Then there is checking to make sure the hyphen can only be at the beginning and only allowing 1 decimal point, etc.  It can get to become quite the headache with all of the different things to look for.

I found a post on Stackoverflow and I was intrigued by one of the solutions using the keyup approach, test the data, and then remove any non numerics from it. There was some pretty nifty regex on there, but a lot of them still seemed to have problems allowing more than 1 decimal and the such. Someone had mentioned about just using jQuery.isNumeric(). I decided to write an example of how this could be done using the jQuery function.

$(document).on('keyup', '.numeric-only', function(event) {
   var v = this.value;
   if($.isNumeric(v) === false) {
        //chop off the last char entered
        this.value = this.value.slice(0,-1);
   }
});

This will force the field to only contain numeric values. The one down side of doing it this way is that you see the non numeric char quickly appear and disappear. This is a great solution as long as that does not bother you.

Here is an example fiddle where you can see it in action.

Recently I started to write my CodeIgniter helper’s to use classes with static methods instead of writing global functions. This stops from having to check if the function name you are about to use already exists, and also allows the use of PHP namespaces if you desire.

Here is a example of how the helper functions are normally setup:

    if( !function_exists('longUniqueString')) {
            /**
          * Provides an extra long random unique String
          * 
          * @param $iterations (default 3)
          * @return String
          *          Random String
          */
         function longUniqueString($iterations = 3) {
             get_instance() -> load -> helper('string');
             $s = '';
             for($i = 0; $i < $iterations; $i++) {
                 $s .= random_string('unique');
             }

             return $s;
         }
    }

Here is the static method way of doing the same thing:

    class CMUtils {


        /**
         * Provides an extra long random unique String
         * 
         * @param $iterations (default 3)
         * @return String
         *          Random String
         */
        public static function longUniqueString($iterations = 3) {
            get_instance() -> load -> helper('string');
            $s = '';
            for($i = 0; $i < $iterations; $i++) {
                $s .= random_string('unique');
            }

            return $s;
        }
    }

The name of the php helper file can be anything you want. Let’s say this particular helper was called utils_helper.php . The code to call the helper would go something like this

    $this -> load -> helper('utils');
    $myStr = CMUtils :: longUniqueString();

0 3453

Occasionally it is necessary to obtain information about the table in a db schema to perform dynamic operations on the data. For example: if trying to save to a numeric db field, automatically validate to make sure the data being received is numeric. I ran across 2 items that I wanted to be able to get the information on for a column, but they were not available in the CI Meta Field Data.

The 2 pieces of information that I really needed to know were:

  1. Is this an auto incremented field?

  2. Does this field allow NULL?

I extended the CI_Model with MY_Model and added this method:

    protected function getTableMetaData($table) {


            //Replaced the default CI field_data so that we could determine if the field is a auto_increment

             /*
                Example object in the MetaData

                   stdClass::__set_state(array(
                 'Field' => 'coupon_no',
                 'Type' => 'bigint(20)',
                 'Null' => 'NO',
                 'Key' => 'PRI',
                 'Default' => NULL,
                 'Extra' => 'auto_increment',
              ))*/

    $fields = $this -> db -> query('DESCRIBE ' . $table) -> result();
            $md = array();
            foreach($fields as $field) {
                preg_match('/([a-zA-Z]+)((d+))?/', $field->Type, $matches);

                $type = (array_key_exists(1, $matches)) ? $matches[1] : NULL;
                $length = (array_key_exists(2, $matches)) ? preg_replace('/[^d]/', '', $matches[2]) : NULL;

                $F              = new stdClass();
                $F->name        = $field->Field;
                $F->type        = $type;
                $F->default     = $field->Default;
                $F->max_length  = $length;
                $F->primary_key = ( $field->Key == 'PRI' ? 1 : 0 );
                $F->auto_increment = strripos($field -> Extra, 'auto_increment') !== FALSE ? 1 : 0; 
                $F->allow_null = $field->Null === 'YES' ? TRUE : FALSE;

                $md[] = $F;
            }




        return $md;

    }

The 2 new properties on the field data are auto_increment which is a boolean and allow_null which is also a boolean. This is MySQL specific, so it would have to be tweaked for other DB’s.

0 6405

I recently made some updates to Ion Auth 2 to allow the user to login with their username or email address.  This was accomplished by creating another config setting called identity_alt.  This is optional and can be used to specify a secondary column which the user can use for their login. I am utilizing it for the email field, but really it can be linked to any other column on the user table.  This enhancement will force this secondary column to be unique for new users if it is specified.  

I have done a pull request to incorporate this into the core ion Auth code, and there is some debate on whether or not it should be there.  Please go there and weigh in, we would appreciate your feedback.

Feel free to grab the update from my fork if you would like to get going on it now.

0 4092

This morning I was creating a extra small bootstrap button linked with a drop down menu. I was really tight on space and noticed that the font size on the drop down menu did not correspond with the class that was put on the button to change it’s size. Here is a snippet of CSS that can be included to accomplish this.

.btn.btn-xs + ul.dropdown-menu > li > a {
    font-size: 12px;
}

The CSS Selector Explained

The selector is is looking for a button that contains the classes “btn” and “btn-xs”. The “+” looks for the first sibling element(on the same hierarchical level) to be a <ul> tag containing the css class “dropdown-menu”. It then must have a <li> directly under the <ul> followed by a <a> tag directly under the <li>. Phew, got all that…

I used firebug to look at the font-size that was being applied to the “btn-xs” by bootstrap and matched it.

Here is a fiddle I whipped up if you would like to see it in action. This same technique could be applied for the other bootstrap buttons sizes.

3 8901

Today I got to write a jQuery plugin that styles a select with hierarchical data. The markup would normally look like this in HTML:

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>

You can see the result of this over at w3schools

This looks cool, but what if you want to allow the user to select the optgroup telling the back end script to grab that level and all under it? I whipped up a quick plugin which works off of data attributes to describe the hierarchy. Here is what the structure of the html looks like:

<select id="hierarchySelect" class="form-control">
    <option data-isparent="true"  data-level="1">Main Dept 1</option>
    <option data-isparent="false" data-level="2">Sub 01</option>
    <option data-isparent="false" data-level="2">Sub 02</option>
    <option data-isparent="true"  data-level="2">Sub 03</option>
    <option data-isparent="false" data-level="3">Sub of Sub</option>
    <option data-isparent="true"  data-level="1">Main Dept 2</option>
    <option data-isparent="false" data-level="2">Sub 01</option>
    <option data-isparent="false" data-level="2">Sub 02</option>
    <option data-isparent="false" data-level="2">Sub 03</option>
</select>

The data-isparent should be flagged as true when there are child options under it. The plugin assumes that the options are already in the correct order. The data-level describes how many levels deep the option is. This assists in the indentation of the option. The default indentation is 25px, but can be overridden in the options of the plugin.

$("#hierarchySelect").selectHierarchy();

Here is a working fiddle that can be used to see the plugin in action.

Here is a link to Download the plugin. I want to build in some additional options and push it out to github when I have a chance. I will update this post when that happens. In the mean time, feel free to use it however you would like.

0 5359

I recently needed to determine if a library was loaded in CI form my Model. I have the CI Rest library using the same model for a query and wanted to change the query if the system had a user logged in. I simply wanted to check and see if the Tank Auth library was loaded and grab the user id from it if it was. I ended up using the PHP function class_exists.

    if(class_exists('Ion_auth')) {
        //Include user specific query stuff here
    }

23 26237

I have been working on a project in PHP / CodeIgniter that I CANNOT wait to tell you guys about…

I have been developing some sweet CI libraries for this project and have decided to give some of them back to the community.   This is my first PHP open source contribution and my first solo Github project.

The CodeIgniter DataTable library handles all the DB operations for searching, sorting, paging, etc a jQuery DataTable.  The project can be found on GitHub CodeIgniter-DataTables.

This weekend I will be working on a CI example application that uses this library, and will update this post when it is available.  I have some other useful libraries that will be rolling out soon so stay tuned…
***Update: A full working example can be found here