We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Setting an input type using setAttribute

Hey there,

I'm currently using \Phalcon\Forms\Form and created myself some special elements such as Email or Url (input type="email"/"url") to leverage HTML5 built-in validation for the frontend design. However, I noticed that using

$this->setAttribute("type","email");

does not work. Is it possible to set the type of an input?

Best, Philipp



98.9k

Hi Philipp, the input's type cannot be changed because it's hardcoded in the related Phalcon\Tag method.

You can create new elements that take advantage of the current functionality this way:

First, create a custom helper for that:

<?php

class MyTags extends \Phalcon\Tag
{

    /**
     * Generates a widget to show a HTML5 input[type="email"] tag
     *
     * @param array
     * @return string
     */
    static public function emailField($parameters)
    {
        return self::_inputField('email', $parameters);   
    }

}

Then create a form element using the helper to generate the html:

<?php

use Phalcon\Forms\Element;

class EmailElement extends Element
{
    public function render($attributes=null)
    {

        //Merge the attributes passed in the constructor/setters with the ones here
        $attributes = $this->prepareAttributes($attributes);

        return MyTags::emailField($attributes);
    }
}

https://docs.phalcon.io/en/latest/reference/tags.html#creating-your-own-helpers https://docs.phalcon.io/en/latest/reference/forms.html#creating-form-elements

Works like a charm, thank you! :-)