PHP code example of yiisoft / form-model

1. Go to this page and download the library: Download yiisoft/form-model library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yiisoft / form-model example snippets


use Yiisoft\FormModel\Attribute\Safe;
use Yiisoft\FormModel\FormModel;
use Yiisoft\Validator\Rule\Email;
use Yiisoft\Validator\Rule\Length;
use Yiisoft\Validator\Rule\Required;

final class LoginForm extends FormModel
{
    #[Label('Your login')]
    #[Required]
    #[Length(min: 4, max: 40, skipOnEmpty: true)]
    #[Email(skipOnEmpty: true)]
    private ?string $login = null;

    #[Label('Your password')]
    #[Required]
    #[Length(min: 8, skipOnEmpty: true)]
    private ?string $password = null;

    #[Label('Remember me for 1 week')]
    #[Safe]
    private bool $rememberMe = false;
}

use Psr\Http\Message\RequestInterface;
use Yiisoft\FormModel\FormHydrator;
use Yiisoft\FormModel\FormModel;

final class AuthController 
{
    public function login(RequestInterface $request, FormHydrator $formHydrator): ResponseInterface
    {
        $formModel = new LoginForm();
        $errors = [];
        if ($formHydrator->populateFromPostAndValidate($formModel, $request)) {
            $errors = $formModel->getValidationResult()->getErrorMessagesIndexedByProperty();
        }
        
        // You can pass $formModel and $errors to the view now.
    }
}

use Yiisoft\FormModel\Field;
use Yiisoft\FormModel\FormModel;

echo Field::text($formModel, 'login');
echo Field::password($formModel, 'password');
echo Field::checkbox($formModel, 'rememberMe');

// ...