Archive | Examples

RSS feed for this section

Introduction

Auto-complete sometimes is called auto-suggest because it allows users to quickly find and select from a pre-populated list of values as they type without the user actually typing it in completely.

Thought it is an extremely popular feature, creating it by hand involves extensive client-side javascript and server-side script programming. PHP Autocomplete addresses the issues by making it easy for PHP developers with simple APIs, minimize any custom Javascript that ultimately shortens its programming time.

Your First Autcomplete

In conf.php, simply set PAC_PATH representing the relative or absolute URL to the PHP Autocomplete library.

Assuming phpAutocomplete folder is inside the web root:

define('PAC_PATH','/phpAutocomplete/');

Then include conf.php in on top of the every page.

require_once("../conf.php");

All PHP Autocomplete code will require minimum two lines of PHP code.

$pac = new C_PhpAutocomplete('company');
$pac -> display('SELECT');
  • The first line is to create our PHP Autocomplete object by calling the constructor;
    • the 1st parameter is the unique ID to an existing Select tag
  • The second line is to call display method to render control on the screen.

The complete code:

<?php
require_once("../conf.php");
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Autocomplete Intro</title>
</head>
<body>
   
<?php
$pac = new C_PhpAutocomplete('company');
$pac -> display();
?>

<select id="company">
    <option></option>
    <option id="1">Apple</option>
    <option id="2">Google</option>
    <option id="3">Microsoft</option>
    <option id="4">Facebook</option>
    <option id="5">Twitter</option>
</select>

</body>
</html>

Result:
PHP Autocomplete supports searching and filtering out of the box.

SELECT or INPUT?

The PHP Autocomplete can be attached an existing HTML Select or an hidden input field.When attached to a Select tag, pass “SELECT” to display() method; or “INPUT” when attached to a hidden Input field. The default value value is “INPUT” when left it blank. e.g.

$pac -> display("SELECT");

So when to use SELECT or INPUT? If you want to transform an existing HTML Select tag into auto-complete control, use “SELECT”; otherwise, use “INPUT” referencing to an input type=’hidden’ tag. In order to take advantage of custom data, use “INPUT”, otherwise data is parsed from Select’s option tags.

<?php
$data =
    array(
        array('id'=>1, 'text'=>'Japan'),
        array('id'=>2, 'text'=>'USA'),
        array('id'=>3, 'text'=>'Hong Kong'),
        array('id'=>4, 'text'=>'Canada'),
        array('id'=>5, 'text'=>'Brazil')
    );
$pac = new C_PhpAutocomplete('country', $data);
$pac -> display();
?>
<input type="hidden" id="country">

Under the Hood

PHP Autocomplete use jQuery Select2 library as the choice of weapon. The Select tag is essentially transforms into combination of hidden Input and and Ul tags. The implication is that you cannot no longer use Select related jQuery method. For example to empty a selection instead of using

$("#state").val();

use

$("#state").select2("val", null);

Multiple Selection

By default, PHP Autocomplete allows selection of a single value. To select multiple values, call enable_multiple() method and pass true.

<?php
$data =
    array(
        array('id'=>1, 'text'=>'Japan'),
        array('id'=>2, 'text'=>'USA'),
        array('id'=>3, 'text'=>'Hong Kong'),
        array('id'=>4, 'text'=>'Canada'),
        array('id'=>5, 'text'=>'Brazil')
    );
$pac = new C_PhpAutocomplete('country', $data);
$pac -> enable_multiple(true);    
$pac -> display();
?>
<input type="hidden" id="country">

Note that When attached to a <select> element this value will be ignored and <select> multiple attribute will be used instead.

<?php
$pac = new C_PhpAutocomplete('country');
$pac -> enable_multiple(true);    // will be ignored
$pac -> display('SELECT');
?>
<select id="country" multiple>
    <option id="1">Japan</option>
    <option id="2">USA</option>
    <option id="3">Hong Kong</option>
    <option id="4">Canada</option>
    <option id="5">Brazil</option>
</select>

Combo Box

PHP Autocomplete has combo box built-in. Combo box is a combination of drop-down list and text box. Users can either type a value directly into the text box or choose from a list of existing options.

Combo box feature is not enabled by default. To enable combobox, call enable_combobox() and set parameter to true. Note that the $data definition has the same definition as the previous examples.

<?php
$pac_cb = new C_PhpAutocomplete('combobox', $data);
$pac_cb->enable_combobox(true);
$pac_cb->display();
?>
<input id="combobox" type="hidden" />

Placeholder Text

A placeholder is the displaying text when no value has not set. Simply call set_placeholder() method to set the placeholder text. When placeholder is used for a non-multi-value select box, it requires that you include an empty <option></option> tag as your first option.

Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.

<?php
$pac = new C_PhpAutocomplete('country', $data);
$pac -> set_placeholder('Choose a country name:');
$pac -> display();
?>
<input type="hidden" id="country">

Minimum Input Characters

You can restrict number of input minimum characters required to start a search by calling set_min_input_length() method.

<?php
$pac = new C_PhpAutocomplete('country', $data);
$pac -> set_placeholder('Choose a country name:');
$pac -> set_min_input_length(3);
$pac -> display();
?>
<input type="hidden" id="country">

Tagging Support

PHP Autocomplete supports ability to add choices automatically as the user is typing into the search field known as “tagging”. Tags are the simplest form of data where the id is also the text. This is especially convenient in the tagging use case where the user can quickly enter a number of tags by separating them with token separators.

<?php
$pac_tag = new C_PhpAutocomplete('tags');
$pac_tag -> set_tags(array("red", "green", "blue", "orange", "white", "black", "purple", "cyan", "teal"), array(","," "));
$pac_tag -> display();
?>
<input id="tags" type="hidden" />

The second parameter is the token separators e.g. array(“,”, ” “). In above example, either a space or a comma will separate a string multiple tags. Try typing in the search field below and entering a space or a comma.

Loading Remote Data via AJAX/JSONP

PHP Autocomplete supports loading remote data on the same or difference domain through AJAX. The remote data must be in JSONP format. JSONP is “JSON with padding“, a JSON derivative, used to retrieve JSON across domains.

Select2 has excellent remote data support. PHP Autocomplete goes one step further to make the routine even easier to implement with load_remote_data() method. The method take one parameter that is the URL to the JSONP remote data. As easy as pie. The URL can be either from a local or a remote domain.

<?php
$pac = new C_PhpAutocomplete('remote_data');
$pac -> load_remote_data('http://example.com/phpAutocomplete/examples/sample_remote_data.php');
$pac -> set_placeholder('Enter name');
$pac -> display();
?>
<input id="remote_data" type="hidden" />

File (Remote sample data) must be the following JSONP format.

[ {"id": "1", "text": "BOBA FETT"},{"id": "2", "text": "R2D2"},{"id": "3", "text": "JAR JAR BINKS"} ]

Cascading/Dynamic Dependent/Nested Dropdown

Cascading, or dependent, sometime called nested drop down is a common requirement in web applications in which a select box contents depend on the value in a parent select box. PHP Autocomplete supports nested drop down out of box, unlimited level. With set_child() method, the implementation is straight forward. Everything is done AJAX style, no page ever refreshes.

<?php
$pac6_1 = new C_PhpAutocomplete('country');
$pac6_2 = new C_PhpAutocomplete('state');
$pac6_3 = new C_PhpAutocomplete('city');

$pac6_1->set_child($pac6_2, 'countryStateData');
$pac6_2->set_child($pac6_3, 'stateCityData');

$pac6_1->display('SELECT');
$pac6_2->display();
$pac6_3->display();
?>
Country:
<select name="country" id="country" style="width:100px">
    <option></option>
    <option value="usa">USA</option>
    <option value="canada">Canada</option>
</select>
State:
<input id="state" type="hidden" style="width:300px"/>
City:
<input id="city"  type="hidden" style="width:300px"/>

The key is in data array “countryStateData” and “stateCityData”. The value of the selected value of a parent select box is used as the index value to its child select box.

<?php
$countryStateData =
    array(
        'usa' => array(
            array('id'=>'ca', 'text'=>'CA'),
            array('id'=>'al', 'text'=>'AL'),
            array('id'=>'nj', 'text'=>'NJ')
        ),
        'canada' => array(
            array('id'=>'ab', 'text'=>'AB'),
            array('id'=>'qc', 'text'=>'QC'),
            array('id'=>'bc', 'text'=>'BC')
        )
    );

$stateCityData =
    array(
        'ca' => array(
            array('id'=>'ca', 'text'=>'San Francisco'),
            array('id'=>'al', 'text'=>'Los Angeles'),
            array('id'=>'nj', 'text'=>'San Diego')
        ),
        'al' => array(
            array('id'=>'ab', 'text'=>'test'),
            array('id'=>'qc', 'text'=>'test2'),
            array('id'=>'bc', 'text'=>'city2')
        ),
        'bc' => array(
            array('id'=>'ab', 'text'=>'2342344'),
            array('id'=>'qc', 'text'=>'bc city2'),
            array('id'=>'bc', 'text'=>'bc city333')
    )
);
echo '<script>';
echo 'var countryStateData = '. json_encode($countryStateData).";\n";
echo 'var stateCityData = '. json_encode($stateCityData).";\n";
echo '</script>';
?>

Below is the JavaScript generated from above

<script>
var countryStateData =
{
    "usa": [
        {
            "id": "ca",
            "text": "CA"
        },
        {
            "id": "al",
            "text": "AL"
        },
        {
            "id": "nj",
            "text": "NJ"
        }
    ],


    "canada": [
        {
            "id": "ab",
            "text": "AB"
        },
        {
            "id": "qc",
            "text": "QC"
        },
        {
            "id": "bc",
            "text": "BC"
        }
    ]
};

var stateCityData =
{
    "ca": [
        {
            "id": 0,
            "text": "San Francisco"
        },
        {
            "id": 1,
            "text": "Los Angeles"
        },
        {
            "id": 2,
            "text": "San Diego"
        }
    ],
    "al": [
        {
            "id": 0,
            "text": "test"
        },
        {
            "id": 1,
            "text": "test2"
        },
        {
            "id": 2,
            "text": "city3"
        }
    ],

    "bc": [
        {
            "id": 0,
            "text": "2342344"
        },
        {
            "id": 1,
            "text": "23452345254"
        },
        {
            "id": 2,
            "text": "34345"
        }
    ]
};
</script>

Templating

It’s easy to customize the dropdown with templates. Templating is done with format_results() method and a little bit Javascript.

The following example attaches country_flag to a Select tag. It formats the results using a Javascript function named “formatCountry” to add country flag images.

<?php
$pac7 = new C_PhpAutocomplete('country_flag');
$pac7->format_results('formatCountry');
$pac7->display('SELECT');
?>
<select name="country_flag" id="country_flag">
    <option></option>
    <option value="usa">USA</option>
    <option value="canada">Canada</option>
    <option value="brazil">Brazil</option>
    <option value="hong_kong">Hong Kong</option>
    <option value="japan">Japan</option>
    <option value="united_kingdom">United Kingdom</option>
</select>

formatCountry is a Javascript function name.

<script>
function formatCountry(country) {
    if (!country.id) return country.text; // optgroup
    return "<img class='flag' src='sample_images/" + country.id.toLowerCase() + "_flag.png' style='vertical-align:middle;padding-right:5px' />" + country.text;
}
</script>

PHP Datagrid As Template (Experimental)

phpGrid phpAutocomplete integration

It is even possible to use datagrid generated by phpGrid as the dropdown template. It is currently an experiment feature.

Setup

Before start, You must acquire both phpGrid and phpAutocomplete You can download both Lite versions for FREE.

It’s important to install phpGrid and phpAutocomplete each in a separate folder. Below is the folder structure used in our example. phpGrid and phpAutocomplete resides in different folder inside phpGrid_phpAutocomplete under web root folder htdocs. This is RECOMMENDED folder hierarchy.

htdocs
+-- phpGrid_phpAutocomplete
|   |-- phpGrid
|   |   +-- conf.php
|   |-- phpAutocomplete
|   |   +-- conf.php
|   +-- phpGrid_template.php

Once folder structure is ready. Set up phpGrid SERVER_ROOT value and phpAutocomplete PAC_PATH value in each of their respective conf.php file.

phpGrid conf.php

define('SERVER_ROOT', '/phpGrid_phpAutocomplete/phpGrid');

phpAutocomplete conf.php

define('PAC_PATH', '/phpGrid_phpAutocomplete/phpAutocomplete/');

Programming

Now, we can move on to the actual integration. First all, include both conf.php files on top of the script.

require_once("phpGrid/conf.php");
require_once("phpAutocomplete/conf.php");

First of all, let’s create our datagrid first before it is used as a template inside the autocomplete as a dropdown.

$dg = new C_DataGrid("select * from products", "productCode", "products");
$dg -> set_col_title("productCode", "Product Code");
$dg -> set_col_hidden('productDescription')->set_col_hidden('productScale')->set_col_hidden('productUrl');
$dg -> set_col_img("Image", "/phpGridx/examples/"); // product image
$dg -> display();

Next, create our autocomplete control:

<?php
$pac_pg = new C_PhpAutocomplete('grid_template');
$pac_pg->set_width('900px');
$pac_pg->display();
?>
<input id="grid_template" type="hidden" />

The next step is to set the phpGrid as the template for autocomplete control. Now, how do we go about that? Well, it turns out that Select2 can also take Javascript object as the data property besides JSON data format. We will, again, use template method format_results() with a little bit Javascript.

$pac_pg->format_results('formatGrid');

formatGrid is a Javascript function defined below. The good news is that phpGrid has already done all the formatting for us, so inside the formatGrid, we simply pass our datagrid object that was created from the phpGrid that we created earlier.

// phpGrid has already formatted the grid, just pass the entire object
function formatGrid(obj) {
    console.log(obj);
    return phpGrid_products;
}

The next step is to make the datagrid template selectable inside the dropdown. We can’t do this with the usual format_selection() method because our template is an object encapsulates both data and display format. If you remember, phpGrid has an add_event() method that can be used to handle a number of events including “onSelectRow” event. Bingo!

Once we retrieve the data that we needed from the datagrid, remember to set the value and close the dropdown.

$onSelectRow = <<<ONSELECTROW
function(status, rowid)
{
    $("#grid_template").select2("open");
    productName = phpGrid_products.jqGrid('getCell',rowid,'productName');
    zipCode = phpGrid_products.jqGrid('getCell',rowid,'supplierZip');
    val = 'ID: '+rowid + ' | Product Name: '+productName + ' | Zip Code: '+zipCode;
    $("#grid_template").select2("val", val); // set selected value
    $("#grid_template").select2("close");    // close dropdown
 }
ONSELECTROW
;
$dg->add_event("jqGridSelectRow", $onSelectRow);

We are almost done. If you run the code right now, you will see that both datagrid and the autocomplete are displayed together on the same page. We don’t need to display the datagrid by itself. Let’s hide it using simple CSS.

<style>
    /* must hide the grid from displaying by itself */
    #gbox_products{display:none}
</style>

That’s it!

The COMPLETE sample code

<?php
require_once("phpGrid/conf.php");
require_once("phpAutocomplete/conf.php");
?>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>test</title>
</head>
<body>

<h2>Datagrid Template</h2>

<style>
    /* must hide the grid from display all by itself */
    #gbox_products{display:none}
</style>

<script>
    // phpGrid has already formatted the grid, just pass the entire object
    function formatGrid(obj) {
        return phpGrid_products;
    }
</script>

<?php
$dg = new C_DataGrid("select * from products", "productCode", "products");
$dg -> set_col_title("productCode", "Product Code");
$dg -> set_col_hidden('productDescription')->set_col_hidden('productScale')->set_col_hidden('productUrl');
$dg -> set_col_img("Image", "/phpGridx/examples/");
$onSelectRow = <<<ONSELECTROW
function(status, rowid)
{
$("#grid_template").select2("open");
    phpGrid_products.jqGrid("resetSelection");
    productName = phpGrid_products.jqGrid('getCell',rowid,'productName');
    zipCode = phpGrid_products.jqGrid('getCell',rowid,'supplierZip');
    val = 'ID: '+rowid + ' | Product Name: '+productName + ' | Zip Code: '+zipCode;
    $("#grid_template").select2("val", val);
    $("#grid_template").select2("close");
 }
ONSELECTROW
;
$dg->add_event("jqGridSelectRow", $onSelectRow);
$dg -> display();


$pac_pg = new C_PhpAutocomplete('grid_template');
$pac_pg->format_results('formatGrid');
$pac_pg->set_width('900px');
$pac_pg->enable_combobox(false);
$pac_pg->display();
?>
<input id="grid_template" type="hidden" />

</body>
</html>

Check out the live demo! | Download Integration Example File

Technical Notes

If the page throws an error like this:

Notice: Constant DEBUG already defined in /phpGrid/conf.php on line 2

This is because both phpAutocomplete and phpGrid have DEBUG constant, you need to comment out of them in conf.php

// define('DEBUG', true);

Live Event Debug

You can view the event triggered by PHP Autocomplete for debugging purpose by setting the DEBUG to true.

In conf.php, set DEBUG constant to true

define('DEBUG', true);

Sample output

live event debug log text

Set Initial Selection

To set initial selected value during page load, use set_init_selection() method. The parameter must be an object array with both “id” and “text” properties. You can use it to set initial selected value for both <select> and <input type=”hidden”>, single or multiple selection.

For example:

$pac->set_init_selection(array(
                            array("id"=>"1", "text"=>"Apple"),
                            array("id"=>"5", "text"=>"Twitter")));

Example: Set initial multiple selection for <input type=”hidden”>

<?php
$data = array(array('id'=>1, 'text'=>'Apple'),
    array('id'=>2, 'text'=>'Google'),
    array('id'=>3, 'text'=>'Microsoft'),
    array('id'=>4, 'text'=>'Facebook'),
    array('id'=>5, 'text'=>'Twitter'));

$pac = new C_PhpAutocomplete('init_selection_INPUT', $data);
$pac->enable_multiple(true);    // hidden input only
$pac->set_init_selection(array(
                            array("id"=>"1", "text"=>"Apple"),
                            array("id"=>"5", "text"=>"Twitter")));
$pac->display();
?>
<input id="init_selection_INPUT" type="hidden" value="" />

<script>
    function get_init_selection(ctrl_id){
        alert($(ctrl_id).select2("val"));
        return false;
    };
</script>
<a href="#" onclick="get_init_selection('#init_selection_INPUT2')">show selected value</a>

Lock, Disable Selection

In the event that you need to lock certain selections so that they can’t be removed, you can now pass in “locked” => true when calling set_init_selection(). Note that lock a selection is only possible when multiple selection is enabled.

To disable a selection from selected in the dropdown, add “disabled”=>true to the data source.

In the following example, the selection “Microsoft” is disabled.

<?php
$data = array(array('id'=>1, 'text'=>'Apple'),
    array('id'=>2, 'text'=>'Google'),
    array('id'=>3, 'text'=>'Microsoft', 'disabled'=>true),
    array('id'=>4, 'text'=>'Facebook'),
    array('id'=>5, 'text'=>'Twitter'));

$pac = new C_PhpAutocomplete('lock_selection_INPUT', $data);
$pac->enable_multiple(true);    // hidden input only
$pac->set_init_selection(array(
    array("id"=>"1", "text"=>"Apple"),
    array("id"=>"5", "text"=>"Twitter", "locked"=>true)));
$pac->display();
?>
<input id="lock_selection_INPUT" type="hidden" value="" />