0

In a Model_Page class, extending the Kohana ORM class, I have this rules definition :

public function rules() {
    return array(
        'url' => array(
            array('Model_Page::unique_url', array($this)),
        ),
    );
}

To simplify here, I will just return false from this function, so it should never validate when I try to save/update a page :

public static function unique_url($page) {
  return false;
}

This works as expected, if the value for url is not NULL or not an empty string.

But if I already have a page with an empty url, and that I try to add a new page with an empty url, the unique_url function is ignored, even when forcing a return false.

This could be a bug, but maybe I missed something...? In the Kohana docs, for the unique example, they use a username as an example, but the username also has a not_empty rule, which does not apply here.

Any help/suggestion appreciated!

4

1 回答 1

0

我相信一旦设置了值,就会应用该规则,而不是在保存它时应用该规则。

我有一个类似的问题 - 如果我没有为该字段分配任何值,则过滤器不起作用。我写了自己的保存方法:

public function save(Validation $validation = NULL)
{
    if (!$this->loaded())
    {
        $this->ordering = 0;
    }

    return parent::save($validation);
}

这样,将始终为新创建的对象分配排序,并且我的过滤器将起作用。

这就是我建立另一个模型的方式。这是一个具有唯一公司名称的公司模型。该字段的规则定义如下:

'name' => array(
    array('not_empty'),
    array('max_length', array(':value', 255)),
    array(array($this, 'unique_name'))
)

我有一个方法:

public function unique_name($value)
{
    $exists = (bool) DB::select(array(DB::expr('COUNT(*)'), 'total_count'))
        ->from($this->_table_name)
        ->where('name', '=', $value)
        ->where($this->_primary_key, '!=', $this->pk())
        ->execute($this->_db)
        ->get('total_count');

    return !$exists;
}

它基本上检查是否有任何其他与当前名称相同的公司。也许这会让您了解您的解决方案可能有什么问题。

于 2014-03-04T12:48:20.603 回答