Validation rules for PresenceOf
are automatically set for items for which the Not Null constraint is set on the table definition for the model generated by Phalcon-devtools, but at the same time as the message "name is required" at the time of PresenceOf error It will be automatically done.
You do not have to change the Validation rule of PresenceOf
, but please teach me how to overwrite this error message.
Generate Model with Phalcon-devtools with the following command.
phalcon model user
Even if you do not set the validation rule specially, if you save it without inputting it for the input item name
of Not Null, an error occurs and you can acquire the message "name is required".
To make the error message your own string, add the following to the User model.
$validator = new Validation();
$validator->add(
'name',
new PresenceOf([
'message' => "required",
])
);
It was an assumption to acquire "required" as a error message, but the result does not change and it gets "name is required".
<?php
use Phalcon\Mvc\Controller;
use Phalcon\Validation;
use Phalcon\Validation\Validator\PresenceOf;
class User extends ModelBase
{
/**
*
* @var string
* @Column(type="string", length=767, nullable=false)
*/
public $name;
public function validation()
{
$validator = new Validation();
$validator->add(
'name',
new PresenceOf([
'message' => "required",
])
);
return $this->validate($validator);
}
/**
* Initialize method for model.
*/
public function initialize()
{
$this->setSchema("lashca");
$this->setSource("user");
}
/**
* Returns table name mapped in the model.
*
* @return string
*/
public function getSource()
{
return 'user';
}
/**
* Allows to query a set of records that match the specified conditions
*
* @param mixed $parameters
* @return User[]|User|\Phalcon\Mvc\Model\ResultSetInterface
*/
public static function find($parameters = null)
{
return parent::find($parameters);
}
/**
* Allows to query the first record that match the specified conditions
*
* @param mixed $parameters
* @return User|\Phalcon\Mvc\Model\ResultInterface
*/
public static function findFirst($parameters = null)
{
return parent::findFirst($parameters);
}
}
You could try to set a default value directly into your model variables
/**
*
* @var string
* @Column(type="string", length=767, nullable=false)
*/
public $name = '';
Another thing you could do is setup the default value from the database directly and pass the 'default' RawValue as value
protected function beforeValidationOnCreate() {
if (empty($this->name)) {
$this->name = new \Phalcon\Db\RawValue('default');
}
}
Finally you can disable the default phalcon validation
public function initialize() {
$this->setup(array('notNullValidations' => false));
}