Below is an example of a simple registration form. It will show the form and on submit, it will validate the input and send a registration email on validation success.
In this section we will learn how to:
Add the following route to routes.php and change the module name.
Router :: get('registration', 'registration.index') -> module('{YOUR-MODULE-NAME}') -> controller('Registration') -> action('register');
Create a file called "ControllerRegistration.php" in "modules/{YOUR-MODULE-NAME}/controllers".
use sFire\MVC\ViewModel;
use sFire\HTTP\Request;
use sFire\Validator\Form\Validator;
use sFire\Mail\Mail;
public function actionRegister() {
$validator = new Validator('register');
//Check if form is submitted
if(true === Request :: isPost()) {
//Create new validation rules
$validator -> field('name') -> required(true) -> lengthbetween(3, 20);
$validator -> field('email') -> required(true) -> lengthmax(30) -> email();
$validator -> field('password') -> required(true) -> notdifferent('password-same') -> lengthbetween(6, 20);
$validator -> token();
//Check if validation passes
if(true === $validator -> passes()) {
$mail = new Mail();
//Send registration mail
$mail -> send(function($mail) {
$mail -> to(Request :: fromPost('register[email]'), Request :: fromPost('register[name]'));
$mail -> from('email@domain.com', 'My company name');
$mail -> assign('name', Request :: fromPost('register[name]'));
$mail -> render('mail.register.html', 'mail.register.text');
});
//Check if mail is successfully send
if(true === $mail -> success()) {
echo 'success';
}
}
}
$view = new ViewModel('documentation.test');
$view -> assign('errors', $validator -> getMessages());
}
Create a file called "register.tpl" in "modules/{YOUR-MODULE-NAME}/views/register" (create the register folder).
@notempty($errors)
<ul>
@foreach($errors as $field => $error)
<li>{{ $field }}: {{ $error }}</li>
@endforeach
</ul>
@endnotempty
<form action="" method="post">
@form('text', 'register[name]') -> attributes(['placeholder' => @translate('Name')]) -> onerror(['class' => 'error'])
@form('text', 'register[email]') -> attributes(['placeholder' => @translate('Email address')]) -> onerror(['class' => 'error'])
@form('password', 'register[password]') -> attributes(['placeholder' => @translate('Password')]) -> onerror(['class' => 'error'])
@form('password', 'register[password-same]') -> attributes(['placeholder' => @translate('Repeat password')]) -> onerror(['class' => 'error'])
@form('token')
@form('submit', 'register[submit]', @translate('Send'))
</form>
Create two other files called "html.tpl" and "text.tpl" in "modules/{YOUR-MODULE-NAME}/views/mail/register" and add the following line in both files:
Hello {{ $name }}, thank you for registration.
Now you can go to the "register" url we made in routes.php and you should be able to validate the input and retrieve a mail with the name you filled in the form.