Вопрос

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!

Нет правильного решения

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top