We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Create a Form using DataList with autocomplete

Hi! help me please, i need create a Form with DataList from database who allow autocomplete, also allow a value and text attribute.

Example Simple DataList with HTML5:

  <input type="text" name="srch" id="srch" list="datalist1">

 <datalist id="datalist1">

           <option value="Canada" >

           <option value="China">

           <option value="Mexico">

            <option value="United Kingdom">

            <option value="United States of America">

            <option value="Uruguay">


Select with Text and Value Attribute

          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="mercedes">Mercedes</option>
          <option value="audi">Audi</option>


I Found a solution, it seem to work. I could tell if it is wrong or if you can improve

Create a new DataList Element:

class DataListElement extends \Phalcon\Forms\Element implements \Phalcon\Forms\ElementInterface
    public function  __construct( $name, array $attributes)

        parent::__construct($name, $attributes);

     * El atributo que ingresa es un arreglo de tres elementos, sin contar el id que se puede recuperar con $this->getName()
     * [0]: Contiene un arreglo con los atributos que puede tener el input.
     * [1]: Contiene una tabla de la BD
     * [2]: Contiene los campos que va a componer el DataList.
     * @param null $attributes
     * @return string
    public function render($attributes = null)
        $atributosInput = $this->getAttributes ()[0];
        $atributosLista = $this->getAttributes ()[1];
        $campos = $this->getAttributes ()[2];
        $html = "<input type='text' id='" . $this->getName() ."' name='" . $this->getName() ."' list='list_" . $this->getName()."' ";
        foreach($atributosInput as $atributo => $valor)
            $html .= " $atributo = ' $valor '";
        $html .= ">";
        $html .= "<datalist  id=\"list_" . $this->getName() ."\" >";
        foreach($atributosLista as $option => $valor)
            $html .= "<option value=\"" . $valor-> $campos[0]. "\" data-value=\"".$valor-> $campos[1]."\">";
            $html .= "</option>";
        $html .="</datalist>";
        return $html;

Create a element in Form

  $dataListCC = new DataListElement('centro_codigo',
        array(array('placeholder' => 'Ingrese el codigo', 'maxlength' => 50),
            array('centroCosto_id', 'centroCosto_codigo')
    $dataListCC->setLabel('Centro Costo');