Auto-Complete List

An auto-complete list is the typical search bar that provides suggestions underneath it as you type. For an example of this within Apex, visit the Users->Manage User menu of the administration panel. You may create a new auto-complete list with the create auto-complete CLI command, for example:

apex create auto-complete <PACKAGE> <ALIAS>

apex create auto-complete my-shop products

This creates a new file at /src/MyShop/Opus/AutoComplete/Products.php, whichcontains one method named search(). Below is an example class:

<?php
declare(strict_types = 1);

namespace App\MyShop\Opus\AutoCompletes;

use Apex\App\Interfaces\Opus\AutoCompleteInterface;
use App\MyShop\Models\Product;

/**
 * Auto Complete - Products
 */
class Products implements AutoCompleteInterface
{

    /**
     * Constructor
     *
     * All attributes within the <b>ERROR:</b> No 'alias' attribute exists within the function tag. tag are passed to this method during instantiation, 
     * and here you can define various properties (ie. userid, type, et al) to be used in below methods.
     */
    public function __construct(
        private array $attr 
    ) { 

    }

    /**
     * Search options
     *
     * @return Associative array of options to display within the auto-complete list.
     */
    public function search(string $term):array
    {

        // Search products
        $options = [];
        $products = Product::where('name LIKE %ls OR description LIKE %ls ORDER BY name', $term, $term);
        foreach ($products as $prod) {
            $options[$prod->id] = $prod->name;
        }

        // Return
        return $options;
    }

}

This class simply generates an associate array of available options using the given search term, keys being the id# of the result, and value being the name of the result that is displayed within the web browser.

Displaying on Web Pages

You can place the auto-complete lists anywhere withn an Apex rendered view by using the <s:function> tag. Using the above example, the HTML tag to display the auto-complete list would be:

<s:function alias="display_auto_complete" autocomplete="my-shop.products" name="product">

Upon submitting the form, two form fields will be available:

  • product - The display value of the selected item.
  • product_id - The id# of the selected item.