New Elements for Your Forms: Date, Time, Colors, and Floats

6 months ago by David Grudl  

Nette forms bring a range of new interactive elements to their arsenal, making it easier to work with dates, times, colors, and float numbers.

Date and Time

Let's get rid of the dependency on JavaScript date/time pickers. Modern browsers now offer this functionality natively and flawlessly. Therefore, Nette introduces support for them, including comprehensive validation on both the client and server sides. With the new methods addDate(), addTime(), and addDateTime(), you can now easily add elements for entering time data into your forms:

$form->addDate('birthday', 'Date of Birth:');
$form->addTime('alarm', 'Alarm Time:');
$form->addDateTime('meeting', 'Date and Time of Meeting:');

Each of these elements returns a DateTimeImmutable object upon submission. They also allow for easy setting of minimum and maximum dates/times and the option to enter seconds:

$form->addTime('detailedTime', 'Exact Time:', withSeconds: true)
	->addRule($form::MIN, 'No more than an hour back', new DateTime('-1 hours'));

A World Full of Colors

Faced with the task of letting users choose a color? Thanks to the new method addColor(), selecting a color will be a breeze:

$form->addColor('favoriteColor', 'Favorite Color:');

The value is returned in the hexadecimal format #rrggbb. By the way, the Image class can now work with this format as well:

$image = Image::fromBlank(100, 200, ImageColor::hex('#3C8ED7'));

Decimal Precision

For applications where every decimal place matters, there's addFloat(). This element allows users to enter decimal numbers, again with validation on both the client and server sides:

$form->addFloat('price', 'Price:')
     ->setRequired();

The documentation will advise you on how to set the element to accept both dot and comma as decimal separators.

The new features in Nette Forms are here to make working with forms even more pleasant for you. Happy coding!