Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

Kohana 3.3 ORM Validation - unique value not working when value is empty

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe the rule is applied once you set the value, not when you're saving it.

I had a similar issue - the filter wasn't working if I didn't assign any value to the field. I've written my own save method:

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

    return parent::save($validation);
}

this way the ordering would always be assigned for newly created objects and my filter would work.

And that's how I built another model. It's a company model that has a unique company name. Rules for the field are defined like this:

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

And I have a method:

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;
}

It basically checks if there are any other companies with the same name as the current one. Maybe this will give you the idea of what could be wrong with your solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...