Nette Framework serves as a powerful tool for PHP developers, facilitating the efficient development of web applications. One of the key features of Nette is the easy and secure creation of forms. This article will guide you through the basic steps of creating a form in Nette, from initial setup to the implementation of security measures.
Basics of Form Creation
The first step in creating a form in Nette is defining the form component. Nette Framework provides the Nette\Application\UI\Form
class, which serves as the foundation for all form elements. Here's a simple example to get started:
use Nette\Application\UI\Form;
class ContactFormFactory
{
public function create(): Form
{
$form = new Form;
$form->addText('name', 'Your name:')
->setRequired('Please fill in your name.');
$form->addEmail('email', 'Your email:')
->setRequired('Please fill in your email.');
$form->addTextArea('message', 'Your message:')
->setRequired('Please write a message.');
$form->addSubmit('submit', 'Submit');
return $form;
}
}
Working with the Form in the Presenter
After defining the form, it needs to be integrated into the presenter. In Nette, this is achieved by registering the form component as a factory method and subsequently implementing a response to form submission:
protected function createComponentContactForm(): Form
{
$form = $this->contactFormFactory->create();
$form->onSuccess[] = [$this, 'processSubmittedContactForm'];
return $form;
}
public function processSubmittedContactForm(Form $form, \stdClass $values): void
{
// Processing submitted data
}
Validation and Security
Nette provides extensive options for input validation and form security. In addition to basic validations such as field requirement or email format check, you can utilize CSRF protection or CAPTCHA. CSRF protection is enabled by default and ensures that each form contains a unique token, guarding against cross-site request forgery attacks.
$form->addProtection('The time limit has expired, please submit the form again');
Creating forms in Nette is easy and secure thanks to its component-based approach and built-in security features. With the help of the Form
class and integration into the presenter, you can quickly build robust and secure forms for your web applications. Remember to validate inputs and secure your forms to protect your users and data.