Upgrading
Upgrading to Version 4.0
Nette Forms 4.0 requires PHP 8.4 and nette/utils 4.1. If you render forms with Latte, you need Latte 3.1.5 or newer.
New Features
- Meet the new Repeater, a container with a dynamic number of items that the user can add and remove directly in the browser, without anything being sent to the server.
- Validation rules are objects, such as
new Validation\LengthValidator(min: 3), and you can write your own just as easily. - Every error message has a stable identifier, such as
forms.length.min, so translations no longer have to depend on the English text. - New controls addUrl() and addPhone(), and suggestions in a text field via setSuggestions().
- Mapping to classes supports readonly classes and reports a value that has nowhere to go.
Changes in Behavior
Your forms keep working, but some of them may behave differently:
- The maximum length set by
setMaxLength()is now checked on the server too, so a longer text makes the form invalid. - Adding a rule that the control already has, with the same argument, replaces it instead of adding a second one. That's how you
change the message of a rule added by
addEmail()and similar methods. - The
MinLength,MaxLengthandLengthrules onCheckboxList,MultiSelectBoxand multiple upload count the selected items, and their messages speak of items, not characters. addMultiUpload()always returns an array, empty if nothing was uploaded, andsetNullable()can no longer be used with it.addFloat()renders a text field withinputmode="decimal"instead of<input type="number">, so that a decimal comma works in every browser. If you want thenumbertype, set it withsetHtmlType('number')together withsetHtmlAttribute('step', 'any').- The arguments of the built-in rules are checked as soon as the rule is added, so for example
Form::Rangewithout two bounds throws an exception right away, not only when the form is submitted. - When mapping to a class, a value with no property or constructor parameter to go to throws an exception, as does a required parameter without a value.
- The
Form::initialize()method was removed. The form creates the HTTP request by itself; if you need to pass your own, use setSubmissionSource().
Error Messages and Translations
- The translator receives the default messages the same way as before, that is the English text of version 3 and the number, so existing translations work unchanged. You can now translate them by stable identifiers, see Translating. Without a translator, the English text of a few messages has changed (images, the type of an uploaded file, a length with equal bounds, the number of selected items).
- The
Nette\Forms\Validator::$messagesarray is empty by default and contains only the texts you override. Your overrides work as before. - The
SelectBox::ValidandUploadControl::Validconstants now contain message identifiers (forms.selectBox,forms.upload) instead of the former strings; this matters only if you used their values literally.
JavaScript
- The script is now distributed only as the npm package
nette-forms; the Composer package no longer contains thesrc/assets/netteForms.jsfile. Load it from the CDN asnette-forms@4, or install it via npm, see JavaScript Validation. - The package defines its exports, so it can only be imported as
nette-forms, not by a path to a file inside it. - The
Nette.webalize()function was removed.
Latte
- The
{formContainer}and{formContext}tags are deprecated, use{form scope name}instead. - The
{formPrint}and{formClassPrint}tags are deprecated, callNette\Forms\Blueprint::latte($form)andNette\Forms\Blueprint::dataClass($form)instead. - Arguments of the
{input}and{label}tags are separated from the name by a comma:{input name, class: foo}. The form without a comma is deprecated.
Removed and Deprecated
- The
CsrfProtectionclass was removed together with the constants related to it. Protection against CSRF is built into the form, see Vulnerability Protection. - The
IControl,IFormRendererandISubmitterControlaliases were removed, useControl,FormRendererandSubmitterControl. - The uppercase constants such as
Form::FILLEDnow report a deprecation, useForm::Filledetc. The same applies to the methods deprecated in 3.x versions:addImage(),setAttribute(),setType(),getSeparatorPrototype(),addOptionAttributes(),getUnsafeValues()andaddProtection(). - The
Validator::validate*()methods are deprecated, use the validator objects from theNette\Forms\Validationnamespace.
For Authors of Custom Controls and Renderers
Submitted data now travels to the controls layer by layer through the containers, which is exactly the mechanism that made Repeater possible. Nothing changes for ordinary form usage; the change concerns exclusively authors of custom form controls and low-level data reading:
- The
Form::getHttpData()method is deprecated. All submitted data is returned bygetSubmittedData()(beware, raw and unsanitized) and reading individual values is shown in the low-level fields chapter. - The protected
BaseControl::getHttpData()method for custom control authors is deprecated, the replacement isgetSubmittedValue(). The optional second parameter is no longer a part of the HTML name, but a key:
// 3.x
$value = $this->getHttpData(Form::DataLine);
$day = $this->getHttpData(Form::DataLine, '[day]');
// 4.0
$value = $this->getSubmittedValue(Form::DataLine);
$day = $this->getSubmittedValue(Form::DataLine, 'day');
- The
Form::DataKeysconstant was renamed toForm::DataArray(the old name remains as a deprecated alias) and a newForm::DataListconstant takes over the former meaning of an HTML name ending with[]: it returns an array of values renumbered from zero. - The
Helpers::extractHttpData()method is deprecated, sanitization of raw data is now provided byHelpers::sanitizeData(). - The value of a control is read using the component name. An overridden HTML
nameattribute works as in 3.x, i.e. as an absolute pointer into the submitted data. Custom controls that overrode thegetHtmlName()method itself instead of the attribute must newly adjust the data reading as well.
The deprecated methods still work and report a deprecation notice when called. The getSubmittedValue() method as
well as its deprecated predecessor getHttpData() on a control work correctly even inside a Repeater.
Other changes for those who extend the library:
- The
Controlinterface declares everything the framework calls on a control, such asloadHttpData(),isFilled(),getRules(),getControl()orgetLabel(). A class that implements the interface directly must add the missing methods; descendants ofBaseControlhave them. - Native types were added throughout the library, so methods you override need matching signatures.
Helpers::exportRules()is deprecated, useClientRuleExporter::export().- When a rule is added,
TextInput,TextAreaandUploadControlno longer write thetype,maxlength,min,max,patternoracceptattributes intogetControlPrototype(); they are derived from the rules when the control is rendered. Ruleis a readonly object whose properties are set in the constructor, and a filter added byaddFilter()is represented by aValidation\CallbackFilterobject instead of a closure.Container::addComponent()accepts only form controls and containers.- The
BaseControl::$disabledproperty is abool; choice controls keep their disabled items separately.
The complete list of changes, including those affecting only rare cases, can be found in the upgrading guide in the repository.
Upgrading to Version 3.3
- the automatic CSRF protection switched from
isSameSite()toisFrom(FetchSite::SameOrigin)and became stricter: requests coming from subdomains no longer pass - thanks to that,
addProtection()is no longer needed, because the automatic protection covers the same cases; omit it in new forms and feel free to remove it from the existing ones
Why tokens in the session are no longer necessary is explained in the article Quarter Century of CSRF.
Upgrading to Version 3.1
getValues()returns only the validated controls; if you need the values of all controls regardless of validation, use the new methodgetUntrustedValues()- the
$valuespassed to theonSuccessandonClickhandlers likewise contain only the validated controls - standalone forms are automatically protected against CSRF by a cookie with the SameSite flag; you can allow submission from
another origin using
allowCrossOrigin() - the
Form::URLrule now completes a missing protocol withhttpsinstead ofhttp Form::addImage()was renamed toaddImageButton()Checkbox::getSeparatorPrototype()was renamed togetContainerPrototype()- forms no longer create the
$_formvariable in templates
More about these changes in the article News in Nette Forms 3.1.
Upgrading to Version 3.0
- all form controls are optional by default now (this change was introduced in Nette 2.4), so you can remove
setRequired(false) - be sure to update
netteForms.jsto version 3 (npm install nette-forms) ChoiceControl::$checkAllowedValuesandMultiChoiceControl::$checkAllowedValueshave been replaced by the methodcheckDefaultValue()
Upgrading to Version 2.4
- if a control has a rule via
addRule()(i.e. it is effectively mandatory), you must also mark it as mandatory viasetRequired(); also,setRequired(false)now makes the control optional, which replacesaddCondition($form::FILLED)branches - the validators
Form::EMAIL,URLandINTEGERautomatically change the HTMLtypeattribute toemail,url, andnumberrespectively - negative validation rules are deprecated; the alternative for
~Form::FILLEDisForm::BLANK, and~Form::EQUALcan be replaced withForm::NOT_EQUAL - the internal parameter
dois now sent via POST as_doto avoid a collision - the internal underscored variables such as
$_formare deprecated - remember to update
netteForms.js
Upgrading to Version 2.3
- internal filtering methods such as
Nette\Forms\Controls\TextBase::filterFloatwere removed - internal validation methods such as
TextBase::validateFloatwere moved toNette\Forms\Validator, as wasRules::$defaultMessages - Buttons and Hidden fields are generated without an HTML ID; if you want an ID, set it via
setHtmlId() - RadioList items are generated without an ID too; you can enable it via
$radioList->generateId = true - filters added via
TextBase::addFilter()are processed during validation, and you can now add filters to conditions:$input->addCondition(...)->addFilter(...)