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



84.6k

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);
    }
}

http://docs.phalconphp.com/en/latest/reference/tags.html#creating-your-own-helpers http://docs.phalconphp.com/en/latest/reference/forms.html#creating-form-elements

Works like a charm, thank you! :-)