Skip to content

MAutoComplete

Overview

MAutoComplete is a user interface component that provides automatic completion suggestions for text fields. It is particularly useful for search or selection fields where users need to choose from a large list of options.

Examples:

Features

  • Real-time autocomplete suggestions
  • Customizable appearance and behavior
  • Support for optional validation button
  • Customizable JavaScript event handling
  • Responsive and modern user interface

Basic Usage

// Required JavaScript functions
<script>
    var 'select' = function(selectedItem){
        console.log("Selected item:", selectedItem['id']);
        // Update your interface here
    };
</script>
<?php
use mlib\ui\autocomplete\MAutoComplete;

// Define the relative path to the directory containing assets
MAutoComplete::registerAssetsPath('/path/to/assets/mautocomplete');

// Display the autocomplete input field
MAutoComplete::display(
    'my_autocomplete_field',               // Field ID
    '/path/to/your/search.php',            // Search script URL
    array(                                 // JavaScript functions
        'onSelect' => 'select'
    )
);
?>

Server-side Search Script

Your search script should return a JSON array of matching results. Example in PHP:

// Example search script (search.php)
$names = array('Dupont', 'Durand', 'Martin', 'Lefevre', 'Dupond', 'Doe', 'Charles', 'Henry', 'Louis', 'Philippe');
$firstNames = array('Jean', 'Michel', 'Luc', 'Matthieu', 'Paul', 'Judas', 'Jacques', 'Pierre', 'Thomas', 'Philippe');

$search = isset($_GET['name']) && preg_match('/^[A-Za-z]+$/', $_GET['name']) ? $_GET['name'] : null;

$result = array();
if($search){
    for($i = 0; $i < count($names); $i++){
        if(str_starts_with(strtolower($names[$i]), strtolower($search))){
            $result[] = array('id' => $i, 'displayname' => $firstNames[$i].' '.$names[$i]);
        }
    }
}
header('Content-Type: application/json');
echo json_encode($result);

Advanced Options

Add a Validation Button

$options = [
    'button' => true,                              // Show a button
    'button_label' => 'Search',                    // Button label
    'button_icon' => '/path/to/icon.png',          // Optional
    'button_color' => '#4285f4',                 // Button background color
    'button_text_color' => '#ffffff',            // Button text color
    'placeholder' => 'Search for a product...',    // Field placeholder
    'min_chars' => 2,                              // Minimum characters before triggering search
    'empty_message' => 'No product found',
    'width' => '500px'                             // Total component width
];

$functions = [
    'onSelect' => 'function(selectedItem) { /* ... */ }',
    'renderResult' => 'function(item) { return "<div>" + item.label + "</div>"; }',
    'onValidate' => 'function() { 
        // Action to perform when clicking the button
        var input = document.getElementById("my_autocomplete_field");
        console.log("Search validated:", input.value);
    }'
];

MAutoComplete::display('my_autocomplete_field', '/search.php', $functions, $options);

Customizing Result Display

You can customize the suggestion display using the renderResult function:

function(item) {
    return `
        <div class="suggestion-item">
            <strong>${item.label}</strong>
            <span class="category">${item.category}</span>
        </div>
    `;
}

Event Handling

onSelect Event

Triggered when an item is selected from the suggestions list.

function(selectedItem) {
    // selectedItem contains the complete object of the selected item
    console.log('ID:', selectedItem.id);
    console.log('Label:', selectedItem.label);

    // Update a hidden field with the selected ID
    document.getElementById('product_id').value = selectedItem.id;

    // Display additional details
    document.getElementById('product_details').innerHTML = 
        `<h3>${selectedItem.label}</h3>
         <p>Category: ${selectedItem.category}</p>`;
}

onValidate Event

Triggered when a user validates the search. The event is attached to the validation button on the right of the input field, if present.

function() {
    // Action to perform when validating the search
    var input = document.getElementById("my_autocomplete_field");
    console.log("Search validated:", input.value);

    // Can be used to submit a form or perform additional action
}