That is my code:
app/forms/MyForm.php
<?php
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Password;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\StringLength;
use Phalcon\Validation\Validator\Regex;
use Phalcon\Validation\Validator\Uniqueness;
class MyForm extends Form
{
public function initialize()
{
$name = new Text('name', [
'minlength' => 3,
'maxlength' => 30,
'placeholder' => 'Name'
]);
$username->addValidators([
new StringLength([
'messageMinimum' => 'The name is too short',
'min' => 4
]),
new Regex([
'message' => 'The name is required',
'pattern' => '/^[a-zA-Z0-9-_.]+$/',
'cancelOnFail' => true
]),
new Uniqueness([
'model' => 'Users',
'message' => 'Sorry, this name already taken.'
])
]);
$this->add($name);
$password = new Password('pass', [
'minlength' => 2,
'placeholder' => 'password'
]);
$password->addValidators([
new PresenceOf([
'message' => 'The password is required'
]),
new StringLength([
'messageMinimum' => 'The password is too short',
'min' => 3
])
]);
$password->clear();
$this->add($password);
}
}
app/controllers/RegisterController.php
<?php
use Phalcon\Mvc\Controller;
class RegisterController extends Controller
{
public function indexAction()
{
$form = new MyForm;
if ($this->request->isPost()) {
$user = new Users;
$user->assign([
'name' => $this->request->getPost('name', ['string', 'striptags']),
'pass' => $this->request->getPost('pass')
]);
if ($user->save()) {
return $this->response->redirect('register/done');
}
$this->flash->error($user->getMessages());
}
$this->view->form = $form;
}
public function doneAction()
{
return 'Done!';
}
}
But the validation has always passed and website always returned "Done!".
I tried to use
if ($form->isValid($_POST)) { ... }
<?php
// ...
public function indexAction()
{
// ...
if ($this->request->isPost()) {
if ($form->isValid($_POST)) {
// ...
}
}
// ...
}
// ...
But it returnes this error:
Exception: Model of record must be set to property "model"
I hope for your support :)
P.S. My version of Phalcon - 2.1