Obsah
(this page is translated by Google; We're working hard on a human translation)
Nette\Forms
Class Nette\Forms easier to create and process Web forms in your applications.
Class Nette\Forms\Form is intended for independent use outside of net. To use the form on the presenter, take advantage of it derived class Nette\Application\AppForm , which adds a service handler presenter.
What can do?
- clearly describe the form and the elements
- define validation rules, conditions and filters
- create custom validation rules
- validate the data sent to the server and client (ie JavaScript)
- can provide their service to the JavaScript
- folding form under their own conditions
- grouping of elements into groups
- Some schemes rendering forms
- Multilingual support
Nette Framework places a strong emphasis on security applications, and therefore efforts are made for security forms. Makes it completely transparent, requires no manual setting and I dare say that in this area has a large advantage over other frameworks. Protects your applications from attack by Cross-Site Request Forgery (CSRF), filtered from the input control characters, to make sure that all text entries are valid UTF-8 string that the items identified in the select boxes are indeed offered, it will automatically trim the gap to single-line text box, etc.
Getting Started
First, we show how to create a simple form, he set validation rules and how to draw.
Create a form
Start by creating a form:
$form = new Form; This form is created by the HTTP POST method sends the same page on which it is located. Of course the method also can change the destination URL:
$form ->setAction( '/submit.php' );
$form ->setMethod( 'get' ); The form is sent using HTTP GET to the address /submit.php .
How to set HTML tag attributes <form> next? Method getElementPrototype() returns the element in the form Nette\Web\html object, which is easy to operate:
$form ->getElementPrototype()->id = 'login-form' ; Form elements
There are two ways to add new controls to the form. First, we can use that form is a descendant of Nette\ComponentContainer , so instances of elements can be added using addComponent (), or can be used even easier way in the form of ready-made factories addText () addPassword (), etc. Example:
$form = new Form();
$form ->addText( 'name' , 'Your name:' );
$form ->addText( 'age' , 'Your age:' , 5 );
$form ->addCheckbox( 'send' , 'Ship to address:' );
$form ->addSelect( 'country' , 'Country:' , $countries );
$form ->addMultiSelect( 'category' , 'Categories' , $categories ); // select s atributem multiple If for some reason we need to edit the html form element attributes, you can pull methods getControlPrototype() and getLabelPrototype() and work with them just like with the object html . You can also get similarly Html Form object itself.
$name = $form [ 'name' ]->getControlPrototype(); // htmlObject controlu
$name -> class ( 'anotherclass' ); // alternativně: $name->class = 'myclass';
$nameLabel = $form [ 'name' ]->getLabelPrototype(); // htmlObject labelu
$nameLabel ->setText( 'Nette' );
$htmlForm = $form ->getElementPrototype(); // htmlObject formuláře
$htmlForm -> class ( 'superForm' ); // nebo rovnou: $form->getElementPrototype()->class('superForm'); Validation rules
Methods addRule () and addCondition () ...:
$form = new Form();
$form ->addText( 'name' , 'Your name:' )
->addRule(Form::FILLED, 'Enter your name' );
$form ->addText( 'age' , 'Your age:' , 5 )
->addRule(Form::FILLED, 'Enter your age' )
->addRule(Form::NUMERIC, 'Age must be numeric' )
->addRule(Form:: RANGE , 'Age must be in range from %d to %d' , array ( 10 , 100 ));
$form ->addCheckbox( 'send' , 'Shipping address:' )
->addCondition(Form::EQUAL, TRUE )
->toggle( 'sendBox' ); // toggle HTML element 'sendBox'
$form ->addText( 'email' , 'Email:' , 35 )
->setEmptyValue( '@' )
->addCondition(Form::FILLED) // conditional rule: if is email filled, ...
->addRule(Form::EMAIL, 'E-mail is not valid' ); // ... then check email
$form ->addText( 'city' , 'City:' , 35 )
->addConditionOn( $form [ 'send' ], Form::EQUAL, TRUE ) // if $form['send'] is checked
->addRule(Form::FILLED, 'Enter your shipping address' ); // $form['city'] must be filled
$form ->addSelect( 'country' , 'Country:' , $countries )->skipFirst(); // skip first option
// must be declared, if you want use skipFirst
$form [ 'country' ]->addRule(Form::FILLED, 'Select your country' ); Methods addRule () and addCondition () as the name of the validation operation, or accept the name of a callback function static, which makes it possible to use custom validation rules.
$form = new Form();
$form ->addText( 'name' , 'Text:' , 10 )
->addRule( 'MyClass::myValidator' , 'Value %d is not allowed!' , 11 ) All the JavaScript support was vyseparována into separate classes. This makes it possible to create a custom validator or JavaScript handling events can be easily connected with the form generated by a JavaScript framework, and the like. ( see forum )
Each HTML form element before the rendering can be arbitrarily adjusted. Provide access to methods getControlPrototype () and getLabelPrototype () which returns an object of type Nette\Web\html.
$form ->addText( 'name' , 'Text:' , 10 );
$form [ 'name' ]->getControlPrototype()->style = "background: blue" ; We need to find a form element id, the method can be used getHtmlId ().
Grouping of
Grouping of elements is easy - just create a group and add any elements to it:
$form ->addGroup( 'Personal data' )
->add( $form [ 'name' ], $form [ 'age' ], $form [ 'gender' ], $form [ 'email' ]); Actually it's even easier. After the new group, this becomes active, and each newly added element is also added into it. So you can build the form as follows:
$form = new Form;
$form ->addGroup( 'Personal data' );
$form ->addText( 'name' , 'Your name:' );
$form ->addText( 'age' , 'Your age:' );
$form ->addText( 'email' , 'E-Mail:' )->emptyValue = '@' ;
$form ->addGroup( 'Shipping address' );
$form ->addCheckbox( 'send' , 'Ship to address' );
$form ->addText( 'street' , 'Street:' , 35 );
$form ->addText( 'city' , 'City:' , 35 );
$form ->addSelect( 'country' , 'Country:' , $countries ); The group, which represents the class FormGroup, a set of elements IFormControl without specific semantic meaning. Thus the importance it gives to such rendering routine that draws the elements grouped in a fieldset element, and so on.
The current group can be set using Form::setCurrentGroup .
$form ->setCurrentGroup( $form ->getGroup( 'název skupiny' )); Or do you smarter:
$group = $form ->addGroup( 'název skupiny' );
// ...
$form ->setCurrentGroup( $group ); When you enter the parameter value of NULL will be awarded to the other elements of any group.
Rendering forms
Form defines the method render() and can draw the structures echo $form .
echo $form ; It is possible to define custom rendering handler $form->setRenderer($ownRenderer) , which is the object interface IFormRenderer . The default is rasterizer ConventionalRenderer not be explicitly set.
Form Processing
// definice
$form = new Form();
$form ->addText( 'name' , 'Your name:' );
$form ->addSubmit( 'ok' , 'Send' )
->onClick[] = 'OkClicked' ; // nebo 'OkClickHandler'
$form ->addSubmit( 'cancel' , 'Cancel' )
->setValidationScope( FALSE )
->onClick[] = 'CancelClicked' ; // nebo 'CancelClickHandler'
// alternativa:
$form ->onSubmit[] = 'FormSubmitted' ; // nebo 'FormSubmitHandler'
if (! $form ->isSubmitted()) {
// první zobrazení, nastavíme výchozí hodnoty
$form ->setDefaults( $defaults );
}
// zavolá obslužné handlery (pozn. od verze 0.9.1)
$form ->fireEvents();
// obslužné handlery:
function OkClicked(SubmitButton $button )
{
// submitted and valid
save( $form ->getValues());
redirect(...);
}
function CancelClicked(SubmitButton $button )
{
// process cancelled
redirect(...);
}
function FormSubmitted(Form $form )
{
// manual processing
if ( $form [ 'cancel' ]->isSubmittedBy()) ...
} This method is suitable for use in MVC implementations Nette\Application .
Serviced handler for onSubmit can be used when the form has no or just one button. In odstatních situations is preferable to use a handler onClick directly on the button.
Handler onClick handler is called before onSubmit . Handlers are called only when it is sending is valid. If the departure is not valid, call the event handlers for onInvalidClick and onInvalidSubmit . Inside OkClicked method is not necessary to verify the validity of the form. Conversely FormSubmitted method can be called even if nevalidního form was sent to the Cancel button.
If the form has been sent to the button (for example, was sent via JavaScript), or the face due to a bug in Internet Explorer, Nette is regarded as a submit button the first button form. Therefore, operation using onClick event is reliable.
Serving handlers to trigger the first call to fireEvents() (from version 0.9.1, earlier in the call isSubmitted() ), using intra- Nette\Application processing will ensure the presenter himself. The task method isSubmitted() is to determine whether the form was sent. The form is validated through the method call validate() or isValid() .
Setting the baseline form (if it has not been sent) method setDefaults() nepřemazává other default form element. But the second has an optional parameter, with which it can be done - $erase = TRUE .
After sending and processing the forms should then redirect the page. Prevent the accidental re-send the form to access the browser history from the stand.
Data obtained using Form::getValues contain the values of form buttons, so it can often be directly used for further processing (such as inserting to the database).
Defending against Cross-Site Request Forgery (CSRF)
Attack lies in the fact that the attacker lures the victim to a page that executes a request (re-routing or javascript) to the server on which the victim is recorded. Protection lies in the fact that the request is checked token, whose value can not know the attacker, and therefore it can not slip. This could be a randomly generated number that is stored in session.
Activation of protection is very simple:
$form = new Form;
...
$form ->addProtection([string $message = NULL ], [int $timeout = NULL ]); As parameter it is possible to state the error message text that is displayed to the user if it detects an unauthorized departure.
Token to protect against CSRF attacks is to force the lifetime of the session. This does not preclude the use of multiple windows at once (in one session). Force is not possible to reduce the number of seconds to bring the second parameter.
Defense should be activated whenever the form changes some sensitive data in your application.
See also:
- Nette\Application\AppForm
- Nette\Forms API Reference
- Nette\Forms\Form API reference
- Best Practice: Form buttons
- Custom rendering forms




Jan Tvrdík | 26. 1. 2010, 23:04 | comment
Chybí seznam a popis existujících formulářových prvků.