Skip to content

Commit

Permalink
Allow to set the min/max HTML5 attributes for text fields (see #25)
Browse files Browse the repository at this point in the history
Description
-----------

This is a feature pull request for contao/core-bundle#1622. It changes the current behaviour of `minlength/maxlength` and `minval/maxval` attributes the way that `min/max` HTML5 attributes will be added automatically if the field is a type of `number`.

I am not sure if the implementation is 100% safe and won't cause any side effects, so any feedback is very much welcome!

Commits
-------

e0194fb Allow to set the min/max HTML5 attributes for text form field (contao/core-bundle#1622)
843fc95 Merge branch 'master' into feature/min-max-field-attributes
96a23e0 Fix the coding style
  • Loading branch information
qzminski authored and leofeyer committed Sep 11, 2018
1 parent 45f9c69 commit f7a5ff7
Showing 1 changed file with 53 additions and 1 deletion.
54 changes: 53 additions & 1 deletion core-bundle/src/Resources/contao/forms/FormTextField.php
Expand Up @@ -66,10 +66,36 @@ public function __set($strKey, $varValue)
{
switch ($strKey)
{
// Treat minlength/minval as min for number type field (#1622)
case 'minlength':
case 'minval':
if ($this->type == 'number')
{
$this->min = $varValue;
}
else
{
$this->arrConfiguration[$strKey] = $varValue;
}
break;

// Treat maxlength/maxval as max for number type field (#1622)
case 'maxlength':
case 'maxval':
if ($varValue > 0)
{
$this->arrAttributes['maxlength'] = $varValue;
if ($this->type == 'number')
{
$this->max = $varValue;
}
elseif ($strKey == 'maxlength')
{
$this->arrAttributes[$strKey] = $varValue;
}
else
{
$this->arrConfiguration[$strKey] = $varValue;
}
}
break;

Expand All @@ -87,6 +113,11 @@ public function __set($strKey, $varValue)

case 'min':
case 'max':
$this->arrAttributes[$strKey] = $varValue;
$this->arrConfiguration[$strKey . 'val'] = $varValue;
unset($this->arrAttributes[$strKey . 'length']);
break;

case 'step':
case 'placeholder':
$this->arrAttributes[$strKey] = $varValue;
Expand Down Expand Up @@ -175,6 +206,27 @@ public function __get($strKey)
}
}

/**
* Re-add some attributes if the field type is a number
*/
public function addAttributes($arrAttributes)
{
parent::addAttributes($arrAttributes);

if ($this->type != 'number')
{
return;
}

foreach (['minlength', 'minval', 'maxlength', 'maxval'] as $name)
{
if (isset($arrAttributes[$name]))
{
$this->$name = $arrAttributes[$name];
}
}
}

/**
* Trim the values
*
Expand Down

0 comments on commit f7a5ff7

Please sign in to comment.