Zend Framework 2 – The New HTML5 Form Fields

Zend Framework 2

Introduction

In this tutorial, I’ll be taking you through a few of the new HTML5-specific form elements available in the new Zend Framework 2. We’ll see: how they work, how to use them, so you can also see what they’re like.

This will be coupled with a good set of screenshots – so you know what they look like. By the end of this tutorial, you should be well on your way to being able to have fully HTML5 interfaces in your applications.

If you’re not familiar with forms in Zend Framework 2 yet, check out the online documentation first. Alternatively, read the introductory series here on Malt Blue:

Difficulty

Beginner

Time Required

20 Minutes

Please Note:

The language set on the iPhone in the screenshots in this tutorial is German. This shouldn’t cause any real issues. But, here is a translation of the words that you are not likely to know if you’re not familiar with German:

  • zurück – back
  • weiter – forward
  • fertig – finish/done
  • löschen – clear/delete/empty

Why HTML5 elements?

As the online world becomes more mobile-centric, we need to be both aware of what this means and how we as developers, specializing in the Zend Framework, can implement them in the applications we’re building.

Here are a few facts from the recent Zend Developer Pulse Report:

  • [IDC predicts](http://www.computerworld.com/s/
    article/9219932/MostwillaccessInternetviamobiledevicesby2015IDCsays) that by 2015, more people will access the Internet through a smartphone than a desktop
  • By 2015, mobile app development projects will outnumber native PC projects by a ratio of 4-1
  • A full 91% of application developers plan to deliver content and services to a mobile audience
  • According to IDC:Sales of smart mobile devices – smartphones and tablets – will grow by 20%, generate 20% of all IT sales and drive 57% of all IT market growth.

These are impressive numbers and clearly show 2 things:

  • Where the market is going
  • Why mobile development is a good place to focus your development efforts

So today, let’s dip our toes in the HTML5 & Mobile development waters and get just a taste of what is available to us.

iPhone Warning: If you’re a Windows Phone or Blackberry supporter you may be a little disappointed by what you’re about to see. The screenshots in today’s post primarily focus around iPhone 5. However, I will be including some screenshots from Android, using the HTC One shortly.

The HTML5 Form Elements?

If you’re familiar with the HTML5 specification, you’ll know that there are a number of new elements. In the space that this tutorial has available however, I’ll only be focusing on just a few, specifically input.

These are:

  • Telephone (tel) – control for entering a telephone number; line-breaks are automatically removed from the input value, but no other syntax is enforced. You can use attributes such as pattern and maxlength to restrict values entered in the control.
  • Email – A field for editing an e-mail address.
  • Url – A field for editing a URL. The user may enter a blank or invalid address. Line-breaks are automatically removed from the input value. You can use attributes such as pattern and maxlength to restrict values entered in the control.
  • DateTime (date, datetime, datetime-local) – A control for entering a date and time (hour, minute, second, and fraction of a second) based on UTC time zone.

For further information about each of these fields, and the rest of the specification, check out the documentation over at MDN (Mozilla Developer Network).

Implementing Them

Implementing them is really trivial, no more difficult than implementing any of the other fields that you’ve been implementing up until now. The way that I’ve approached it is through form code, with a minimalist configuration.

A lot of these examples you’ll see are very similar. That’s OK, as there’s generally not a lot that you have to do which is different.

Email

Zend Frameowrk 2 Email Field

What about email? Whether that’s a registration, forgot password or user management form, it’s arguably one of the most important fields in a form.

As you can see, in the image above, when the user clicks in an email field, the keyboard is changed to only provide characters that match the email specification. The email field will validate that value entered in the field represents a valid email address.

View Script

As with the telephone example above, I’ve rendered the email element in the view script using the viewscript form helpers (formLabel and formEmail).

<div class="control-group">
    <?php
    $active = $form->get('eventCategoryActive');
    echo $this->formLabel($active);
    ?>
    <div class="controls">
        <?php
        echo $this->formEmail($active);
        echo $this->formElementErrors($active);
        ?>
    </div>
</div>

Form Code

Now for the code. As with the telephone element, I’m adding the email element to the form by specifying the type as ‘Zend\Form\Element\Email‘. I’ve then specified the name and label values.

$this->add(array(
    'type' => 'Zend\Form\Element\Email',
    'name' => 'userWebsite',
    'options' => array(
        'label' => 'Website',
    )
));

This configuration allows for one email address. If you want to allow for multiple email addresses, then add specify multiple to true in the options array, as follows:

$this->add(array(
    'type' => 'Zend\Form\Element\Email',
    'name' => 'userWebsite',
    'options' => array(
        'label' => 'Website',
        'multiple' => true
    )
));

Url

Zend Frameowrk 2 Url Field

Arguably, after emails (or maybe before), come URLs. Whether it’s a web address, ftp address or similar, they’re one of the most commonly used aspects on the web.

In the screenshot above, you see how the keyboard on the iPhone 5 has changed so that only allowed characters are available, with an extra .com button to help along. This element transparently adds the Zend\Validator\Uri validator, which ensures that the value entered is a value URI.

View Script

Here, I’ve rendered the url field using the formUrl ViewScript helper, as in previous examples.

<div class="control-group">
    <?php
    $active = $form->get('eventCategoryActive');
    echo $this->formLabel($active);
    ?>
    <div class="controls">
        <?php
        echo $this->formUrl($active);
        echo $this->formElementErrors($active);
        ?>
    </div>
</div>

Form Code

As with the previous examples, I’m adding the URL element to the form by specifying the type as ‘Zend\Form\Element\Url‘. I’ve then specified the name and label values.

$this->add(array(
    'type' => 'Zend\Form\Element\Url',
    'name' => 'userWebsite',
    'options' => array(
        'label' => 'Website',
    )
));

DateTime

Zend Frameowrk 2 Date Field

One last example. This one is one that I feel is really important and consequently very helpful for users – the Date & Time field.

How often do we, as developers & designers, have to put in extra work or jump through hoops to ensure that the user enters the correct information when supplying dates and times? Arguably, too often is a pretty close answer. Right?

Well the HTML5 DateTime element goes a long way to cutting this effort down (at least on a Smart Phone). In the screenshot above, you can see that when the user’s given focus to the DateTime field, the keyboard has changed to only allow them to enter a valid date, using the ultra-efficient date input keyboard available under iOS.

Now, all we need to do is to convert one value sent from the form, into an applicable format required to be stored in our datasource (whether MySQL, PostgreSQL, MongoDB or whatever). When the user is finished, the field appears as a select box showing the specified date.

View Script

As with the previous examples, I’ve used the form ViewScript helpers to render the element. Nothing new here.

<div class="control-group">
    <?php
    $active = $form->get('eventCategoryActive');
    echo $this->formLabel($active);
    ?>
    <div class="controls">
        <?php
        echo $this->formSelect($active);
        echo $this->formElementErrors($active);
        ?>
    </div>
</div>     

Form Code

Similarly, with the other elements, I’ve called the add method, passing in an array, specifying the type (‘Zend\Form\Element\Date‘), name and label values for the element, which has done the majority of the heavy lifting for us.

$this->add(array(
    'type' => 'Zend\Form\Element\Date',
    'name' => 'userWebsite',
    'options' => array(
        'label' => 'Website',
    )
));

If we wanted to provide even more guidance to the user, we could have specified a minimum and maximum date range in the additional attributes array (as below). Some examples of where this can be useful are:

  • Users being over or under a certain age
  • Users being within a certain age range
  • Defaulting to a short, meaningful range so the user doesn’t need to search too much

Specifying the Minimum and Maximum Date Range

'attributes' => array(
         'min' => '2012-01-01',
         'max' => '2020-01-01',
 ) 

Telephone

Zend Framework 2 HTML5 Telephone Field

At this point, given the wide differences in international phone number formats, no validation is performed by the browser. However, what we do get is, on mobile devices, a keyboard that is customized to entering the correct type of information.

You can see in the screenshot above that when you set focus in the field, that the keyboard changes to one that only provides options for entering phone number information (including the international dialing prefixes; i.e., +61, +49 etc).

View Script

In the view script output below, you’ll see that I’m using the formTel and formLabel view helpers. This will, assuming that the element is a telephone field, print out a telephone type field.

<div class="control-group">
    <?php
        $active = $form->get('eventCategoryActive');
        echo $this->formLabel($active);
    ?>
    <div class="controls">
        <?php
            echo $this->formTel($active);
            echo $this->formElementErrors($active);
        ?>
    </div>
</div>

Form Code

Now that we have the view script in place, let’s have a look at the code for creating a phone number field. Firstly, I’ve created a new Zend Form object, called $form.

I’ve then called add on this, which adds a new Form Element, specifying the type, name and options. You can see that it’s of type Telephone, the name is userPhone and I’ve set the label value to Phone Number.

$form = new \Zend\Form;

$form->add(array(
    'type' => 'Zend\Form\Element\Number',
    'name' => 'userPhone',
    'options' => array(
        'label' => 'Phone Number',
    )
));

Nothing hard about this one. Now your user has less work to do to enter phone and fax numbers on your forms.

Conclusion

So there we have it. We’ve gone through four of the new HTML5 elements available in Zend Framework 2 (Telephone, Email, URL and DateTime). As we’ve touched on, there are a number of other new elements, including Month, Color, Time, Week and Range.

We’ve seen what they look like in the most popular mobile browser, Safari on iOS, and how they make the job of user input simpler, quicker and easier to complete. You’re now in a position to use the remainder of the new HTML5 elements, as needed, in your applications.

Given the continued growth of smart phones and mobile internet access and the expected usage numbers over the next 5 years, these fields will help ensure that they’re the ones that continue to prosper and are thoroughly enjoyed by users.

For more information about the elements that I’ve used on today’s tutorial, or any of the other elements available in Zend Framework 2, be sure to check out the excellent online documentation.

Till then, share your thoughts, in the comments, about how you’re using the new HTML5 elements in your applications. How are they enhancing your applications? Have your users been giving you positive feedback?

Beginner Tutorial
  • HDMAX786

    Guys just sharing, I’ve found this interesting! Check it out! http://www.hdmax-hi-tec-goods.com/

  • http://webllena.com/ dejan filipovic

    new HTML5 and Zend Framework 2 are really something great!Thanks for this post.

    • http://www.matthewsetter.com/ Matthew Setter

      Not a problem Filip. Glad you like them.

  • Webdevilopers

    I just tried to use the “Telephone” type recognizing that there is no such element (yet?) in the Zend library.

    Quoting your example you state:
    “I’ve then called add on this, which adds a new Form Element, specifying the type, name and options. You can see that it’s of type Telephone, the name is userPhone and I’ve set the label value to Phone Number.”

    But actually you are using the “ZendFormElementNumber” type.

    Is there a reason why this element does not exist yet? Should I user “Number” instead and create a custom validator?

    It looks like I am forced to use the “formtel” view helper since I can’t use the “formrow” helper when there is no element for “tel”. :(

    • http://www.matthewsetter.com/ Matthew Setter

      Hey @webdevilopers:disqus I see now, thanks to yours and m.zam’s comment, that the way I approached this situation was incorrect. Looking at it now, I see a few possible, better, solutions.

      Firstly I could use a Text element, instead of using a number, along with the Telephone view helper. This is because a number element wouldn’t accept all valid input options, such as space and +. I could then set a suitable regex for the pattern attribute of the telephone view helper to enforce validation. Here’s a good selection of regexes as a starting point: http://html5pattern.com/Phones.

      Secondly I could use the telephone view helper without the pattern attribute and create a custom form element, implementing a regex validator either attempting to catch any phone number, which would be quite hard, or country specific. I’m not sure of the work involved in either approach. But either would be an improvement on what I have here.

      I’ll update the article tomorrow mentioning this. Thanks for letting me know.

  • m.zam

    hi, one question, how you define element for decimal number

    can we use ‘ZendFormElementNumber’

    but then how we define the decimal (10,2) – by attribute or by format ?

    thanks in advance

    • http://www.matthewsetter.com/ Matthew Setter

      Thanks for asking. I’ve added a comment below on @webdevilopers:disqus question, which I believe answers yours.