diff --git a/docs/guide/form.md b/docs/guide/form.md index c1f1ba3b0c..c811c107c7 100644 --- a/docs/guide/form.md +++ b/docs/guide/form.md @@ -1,3 +1,96 @@ Working with forms ================== +The primary way of using forms in Yii is [[\yii\widgets\ActiveForm]]. It should be preferred when you have a model +behind a form. Additionally there are some useful methods in [[\yii\helpers\Html]] that are typically used for adding +buttons and help text. + +First step creating a form is to create a model. It can be either Active Record or regular Model. Let's use regular +login model as an example: + +```php +use yii\base\Model; + +class LoginForm extends Model +{ + public $username; + public $password; + + /** + * @return array the validation rules. + */ + public function rules() + { + return [ + // username and password are both required + ['username, password', 'required'], + // password is validated by validatePassword() + ['password', 'validatePassword'], + ]; + } + + /** + * Validates the password. + * This method serves as the inline validation for password. + */ + public function validatePassword() + { + $user = User::findByUsername($this->username); + if (!$user || !$user->validatePassword($this->password)) { + $this->addError('password', 'Incorrect username or password.'); + } + } + + /** + * Logs in a user using the provided username and password. + * @return boolean whether the user is logged in successfully + */ + public function login() + { + if ($this->validate()) { + $user = User::findByUsername($this->username); + return true; + } else { + return false; + } + } +} +``` + +In controller we're passing model to view where Active Form is used: + +```php +use yii\helpers\Html; +use yii\widgets\ActiveForm; + + 'login-form', + 'options' => ['class' => 'form-horizontal'], +]) ?> + = $form->field($model, 'username') ?> + = $form->field($model, 'password')->passwordInput() ?> + +