Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Nette
https://github.com/nette/docs
Admin
Nette documentation provides guides and information for contributing to and understanding the Nette
...
Tokens:
2,327,410
Snippets:
17,343
Trust Score:
7.7
Update:
9 months ago
Context
Skills
Chat
Benchmark
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Nette Framework 2.3 Documentation This project contains the official documentation for Nette Framework version 2.3, a PHP framework for building web applications. The documentation covers core components including the Application layer (nette/application v2.3), Forms (nette/forms v2.3), Utilities (nette/utils v2.3), HTTP (nette/http v2.3), Mail (nette/mail v2.3), and Security (nette/security v2.3). The documentation is structured as a multilingual resource with content available in both Czech and English, formatted in Texy markup language for easy rendering and maintenance. The documentation provides comprehensive guides for developers working with Nette's MVC architecture, form handling, routing system, HTTP request/response management, email sending, security features, and utility classes. Each section contains detailed explanations, practical code examples, and best practices for building secure, maintainable web applications. The project follows a modular structure with separate directories for each major component, making it easy to navigate and contribute to specific areas of the framework documentation. ## Creating a Basic Form with Validation Complete form implementation with server-side and client-side validation, including text inputs, password fields, and validation rules. ```php <?php require 'Nette/loader.php'; use Nette\Forms\Form; $form = new Form; // Text input with required validation $form->addText('name', 'Name:') ->setRequired('Please fill your name.'); // Number input with integer and range validation $form->addText('age', 'Age:') ->setType('number') ->addRule(Form::INTEGER, 'Your age must be an integer.') ->addRule(Form::RANGE, 'You must be older %d years and be under %d.', [18, 120]); // Password with minimum length validation $form->addPassword('password', 'Password:') ->setRequired('Pick a password') ->addRule(Form::MIN_LENGTH, 'Your password has to be at least %d long', 3); // Password verification with equality check $form->addPassword('passwordVerify', 'Password again:') ->setRequired('Fill your password again to check for typo') ->addRule(Form::EQUAL, 'Password missmatch', $form['password']); $form->addSubmit('send', 'Register'); // Set default values $form->setDefaults([ 'name' => 'John Doe', 'age' => 33, ]); // Process form submission if ($form->isSubmitted() && $form->isValid()) { echo 'Form was submitted and passed validation'; $values = $form->getValues(); dump($values); } echo $form; ?> <style> .required label { color: maroon } </style> <script src="netteForms.js"></script> ``` ## Form Component Factory in Presenter Creating reusable form components within presenters using the component factory pattern with event handlers for form submission. ```php <?php use Nette\Application\UI; use Nette\Forms\Form; class HomepagePresenter extends UI\Presenter { protected function createComponentRegistrationForm() { $form = new UI\Form; $form->addText('name', 'Name:') ->setRequired('Please fill your name.'); $form->addPassword('password', 'Password:') ->setRequired('Pick a password') ->addRule(Form::MIN_LENGTH, 'Your password has to be at least %d long', 3); $form->addSubmit('login', 'Sign up'); // Attach success handler $form->onSuccess[] = array($this, 'registrationFormSucceeded'); return $form; } // Called after form is successfully submitted public function registrationFormSucceeded(UI\Form $form) { $values = $form->getValues(); // Process the form data (save to database, etc.) // ... $this->flashMessage('You have successfully signed up.'); $this->redirect('Homepage:'); } } ``` ## Routing Configuration Setting up URL routing with parameters, optional segments, and default actions for creating SEO-friendly URLs. ```php <?php use Nette\Application\Routers\RouteList; use Nette\Application\Routers\Route; // Create route collection $router = new RouteList(); // Specific route for RSS feed $router[] = new Route('rss.xml', 'Feed:rss'); // Route with required parameter $router[] = new Route('article/<id>', 'Article:view'); // Generic route with optional id parameter // presenter defaults to Homepage, action defaults to default $router[] = new Route('<presenter>/<action>[/<id>]', 'Homepage:default'); // Alternative array syntax for defaults $router[] = new Route('<presenter>/<action>[/<id>]', array( 'presenter' => 'Homepage', 'action' => 'default' )); // Route with GET parameters $router[] = new Route('<presenter>/<action> ? id=<productId> & cat=<categoryId>', 'Homepage:default'); ``` ## Router Factory Pattern Recommended approach for configuring application routing using a factory class registered in the DI container. ```php <?php // File: app/router/RouterFactory.php namespace App; use Nette\Application\Routers\RouteList; use Nette\Application\Routers\Route; class RouterFactory { /** * @return \Nette\Application\IRouter */ public function createRouter() { $router = new RouteList(); $router[] = new Route('<presenter>/<action>', 'Homepage:default'); return $router; } } ``` ```neon # File: app/config/config.neon services: router: App\RouterFactory::createRouter ``` ## Presenter Lifecycle and Redirection Implementing presenter action methods with database interaction, error handling, and flash messages. ```php <?php use Nette\Application\UI\Presenter; use Nette\Application\BadRequestException; class ProductPresenter extends Presenter { private $model; public function startup() { parent::startup(); // Initialize variables or check user privileges } public function actionShow($id) { // Executed before renderShow() // Can change the view with $this->setView('otherView') } public function renderShow($id) { // Fetch data from database $product = $this->model->getProduct($id); // Throw 404 if not found if (!$product) { throw new BadRequestException; } // Pass data to template $this->template->product = $product; } public function deleteFormSubmitted($form) { $values = $form->getValues(); // Delete from database $this->model->deleteProduct($values->id); // Flash message (persists after redirect) $this->flashMessage('Item was removed.'); // Redirect with HTTP 302 $this->redirect('Product:list'); // Or redirect with specific HTTP code // $this->redirect(301, 'Product:list'); // Or redirect to external URL // $this->redirectUrl('https://nette.org'); } } ``` ## Form Select Boxes and Radio Lists Creating dropdown selects and radio button groups with hierarchical options and prompts. ```php <?php use Nette\Forms\Form; $form = new Form; // Radio buttons $sex = array( 'm' => 'male', 'f' => 'female', ); $form->addRadioList('gender', 'Gender:', $sex); // Select box with hierarchical options $countries = array( 'Europe' => array( 'CZ' => 'Czech republic', 'SK' => 'Slovakia', 'GB' => 'United Kingdom', ), 'CA' => 'Canada', 'US' => 'USA', '?' => 'other', ); $form->addSelect('country', 'Country:', $countries) ->setPrompt('Pick a country'); // Multi-select $options = array( 'opt1' => 'Option 1', 'opt2' => 'Option 2', 'opt3' => 'Option 3', ); $form->addMultiSelect('options', 'Pick many:', $options); // Checkbox list $form->addCheckboxList('colors', 'Colors:', array( 'r' => 'red', 'g' => 'green', 'b' => 'blue', )); ``` ## Custom Validation Rules Implementing custom validation functions for forms with both PHP and JavaScript validators. ```php <?php use Nette\Forms\Form; // User-defined validation function function divisibilityValidator($item, $arg) { return $item->value % $arg === 0; } $form = new Form; $form->addText('number', 'Number:') ->addRule('divisibilityValidator', 'Number must be divisible by %d.', 8); // Custom validation for entire form protected function createComponentSignInForm() { $form = new Form(); $form->addText('username', 'Username:'); $form->addPassword('password', 'Password:'); $form->onValidate[] = array($this, 'validateSignInForm'); return $form; } public function validateSignInForm($form) { $values = $form->getValues(); if (!$this->authenticator->validate($values->username, $values->password)) { $form->addError('Password does not match.'); } } ``` ```html <!-- JavaScript validator (in template) --> <script> Nette.validators.divisibilityValidator = function(elem, args, val) { return val % args === 0; }; </script> ``` ## Form Conditional Validation Setting up conditional validation rules based on other form elements' values. ```php <?php use Nette\Forms\Form; $form = new Form; // Checkbox that controls email requirement $form->addCheckbox('newsletters', 'send me newsletters'); // Email is only required if checkbox is checked $form->addText('email', 'Email:') ->addConditionOn($form['newsletters'], Form::EQUAL, TRUE) ->setRequired('Fill your email address'); // Password complexity based on length $form->addPassword('password', 'Password:') // If password is not longer than 5 characters ->addCondition(Form::MAX_LENGTH, 5) // Then it must contain a number ->addRule(Form::PATTERN, 'Must contain number', '.*[0-9].*'); // Negated conditions with tilde $form->addText('optional', 'Optional:') ->addRule(~Form::FILLED, 'This field should be empty'); ``` ## Form Rendering in Latte Templates Manual form rendering with custom HTML structure and partial rendering of form elements. ```latte {* Basic form rendering *} {control registrationForm} {* Manual form rendering with custom structure *} {form signForm} <ul class="errors" n:if="$form->hasErrors()"> <li n:foreach="$form->errors as $error">{$error}</li> </ul> <table> <tr class="required"> <th>{label name /}</th> <td>{input name}</td> </tr> <tr class="required"> <th>{label password /}</th> <td>{input password}</td> </tr> <tr> <td colspan="2">{input send}</td> </tr> </table> {/form} {* Using n:name attribute for custom HTML *} <form n:name=signInForm class=form> <p><label n:name=user>Username: <input n:name=user size=20></label> <p><label n:name=password>Password: <input n:name=password></label> <p><input n:name=send class="btn btn-default"> </form> {* Partial rendering of radio buttons *} {foreach $form[gender]->items as $key => $label} <label n:name="gender:$key"><input n:name="gender:$key"> {$label}</label> {/foreach} {* Form container rendering *} {form signForm} <table> <th>Which news you wish to receive:</th> <td> {formContainer emailNews} <ul> <li>{input sport} {label sport /}</li> <li>{input science} {label science /}</li> </ul> {/formContainer} </td> </table> {/form} ``` ## Reusable Form Factory Creating a standalone form factory class for using the same form across multiple presenters. ```php <?php // File: app/forms/SignInFormFactory.php use Nette\Application\UI\Form; class SignInFormFactory { /** * @return Form */ public function create() { $form = new Form; $form->addText('name', 'Name:'); $form->addPassword('password', 'Password:'); $form->addSubmit('login', 'Log in'); // Form processing in factory $form->onSuccess[] = function (Form $form) { $values = $form->getValues(); // Process submitted form here }; return $form; } } // Using the factory in presenter class UserPresenter extends Nette\Application\UI\Presenter { protected function createComponentSignInForm() { $form = (new SignInFormFactory)->create(); // Can modify the form $form['login']->caption = 'Continue'; // Or add additional handlers $form->onSuccess[] = array($this, 'signInFormSubmitted'); return $form; } } ``` ## CSRF Protection and Multilingual Forms Implementing Cross-Site Request Forgery protection and internationalization for forms. ```php <?php use Nette\Application\UI\Form; use Nette\Localization\ITranslator; // CSRF Protection $form = new Form; $form->addText('email', 'Email:'); $form->addProtection('Your session has expired. Please return to the home page and try again.'); // Custom Translator Implementation class MyTranslator extends Nette\Object implements ITranslator { /** * Translates the given string. * @param string message * @param int plural count * @return string */ public function translate($message, $count = NULL) { // Your translation logic here return $message; // placeholder } } // Apply translator to form $translator = new MyTranslator(); $form->setTranslator($translator); // Global validation message customization Nette\Forms\Rules::$defaultMessages[Form::FILLED] = "All fields are obligatory."; ``` ## File Upload and Advanced Input Types Handling file uploads with validation and using HTML5 input types with attributes. ```php <?php use Nette\Forms\Form; use Nette\Utils\Html; $form = new Form; // File upload with image validation $form->addUpload('thumbnail', 'Thumbnail:') ->addRule(Form::IMAGE, 'Thumbnail must be JPEG, PNG or GIF') ->addRule(Form::MAX_FILE_SIZE, 'Maximum file size is 2 MB', 2 * 1024 * 1024); // HTML5 email input $form->addText('email', 'Your e-mail:') ->setType('email') ->setAttribute('placeholder', 'Please, fill in your e-mail address'); // Input with description $form->addText('phone', 'Phone:') ->setOption('description', Html::el('p') ->setHtml('This number remains hidden. <a href="...">Terms of service.</a>') ); // Hidden field $form->addHidden('user_id'); // Button with JavaScript action $form->addButton('raise', 'Raise salary') ->setAttribute('onclick', 'raiseSalary()'); // Image submit button $form->addImage('submit', '/path/to/image'); // Disabled input (not returned in getValues()) $form->addText('email', 'E-mail:')->setDisabled(TRUE); // Omitted input (removes value but doesn't disable) $form->addText('antispam', 'Antispam:')->setOmitted(TRUE); // Setting class and attributes on form $form->getElementPrototype()->id = 'myForm'; $form->getElementPrototype()->target = '_top'; ``` This documentation project serves as a comprehensive reference for developers learning and working with Nette Framework 2.3. The primary use cases include building PHP web applications with the MVC pattern, implementing secure forms with validation, configuring flexible URL routing, managing HTTP requests and responses, sending emails, implementing authentication and authorization, and utilizing utility classes for common tasks. The documentation emphasizes security best practices including automatic CSRF protection, XSS filtering, and UTF-8 validation. Integration patterns focus on the component-based architecture where forms and other UI elements are created as reusable components within presenters. The framework uses dependency injection for configuration, event-driven form processing with onSuccess/onValidate handlers, and a template system (Latte) for rendering views. Developers typically extend base presenter classes, implement component factories, and use the routing system to map URLs to presenter actions while maintaining clean, maintainable code structure throughout their applications.