如何覆盖由Phalcon-Devtools生成的模型的无效项目的错误消息



问题

PresenceOf的验证规则是自动为phalcon-devtools生成的模型在表定义上设置的项目的项目设置必需的 "在存在错误时,它将自动完成。

您不必更改PresenceOf的验证规则,但请教我如何覆盖此错误消息。


概述

  • 使用以下命令生成模型。

    phalcon model user
    
  • 即使您没有专门设置验证规则,如果您将其保存而无需输入输入项目 name of not null,则会发生错误,并且可以获取消息" name需要"。

  • 要使错误消息您自己的字符串,请将以下内容添加到用户模型中。

    $validator = new Validation();
        $validator->add(
           'name',
            new PresenceOf([
               'message' => "required",
            ])
        );
    
  • 这是获取" 必需"作为错误消息的假设,但是结果不会更改并且获得了" 需要名称"。


源代码

<?php
use PhalconMvcController;
use PhalconValidation;
use PhalconValidationValidatorPresenceOf;
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|PhalconMvcModelResultSetInterface
     */
    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|PhalconMvcModelResultInterface
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }
}

环境

  • Centos 7.4(x64)
  • Apache 2.4.6
  • php 7.0.26
  • Phalcon Framework 3.2.4
  • MySQL VER 14.14分布5.6.38

您可以尝试将默认值直接设置为模型变量

 /**
 *
 * @var string
 * @Column(type="string", length=767, nullable=false)
 */
public $name = '';

您可以做的另一件事是直接从数据库中设置默认值,然后将"默认" rawValue作为值

传递
protected function beforeValidationOnCreate() {
    if (empty($this->name)) {
        $this->name = new PhalconDbRawValue('default');
    }
}

最后,您可以禁用默认的phalcon验证

 public function initialize() {
    $this->setup(array('notNullValidations' => false));
}

最新更新