1

Is it possible to create a validation rule in Kohana 3 that will validate the has_many through relationship?

Using the example on the guide page, a blog post can have many categories through the categories_posts table. Is there a validation rule that can be setup in the Post model to verify at least one category was added?

I tried the following:

public function rules()
{
    return array(
        'categories' => array(
            array(array($this, 'has'), array('categories'))
        )
    );
}

because I see that the ORM::has function will return true/false. But I think because 'categories' is a relationship, and not a field, the rule I wrote never gets checked.

Any ideas?

krische
  • 1,010
  • 3
  • 11
  • 17

3 Answers3

1

You must save Post before adding has_many relations. You can check Post for categories after saving, and mark it as draft if they were not set.

biakaveron
  • 5,493
  • 1
  • 16
  • 20
  • Yep, I had that problem. If I tried to add the `has_many` relationship before saving the `Post` I would get a database error because the `Post` didn't have an id yet. – krische Jun 05 '12 at 21:15
  • Thats why relations must be checked outside the standard model validation. – biakaveron Jun 06 '12 at 09:34
0

Woo, good idea. Focus in MVC design pattern. I think that's C business not the M.

if ($post->categories->find_all())
{
   //blablabla
}
alan
  • 241
  • 2
  • 5
  • Or I suppose I could just do `$post->categories->count_all()` and make sure it's greater than 0. I was just hoping it was possible to do with a validation rule. – krische Jun 05 '12 at 17:04
0

Since categories is external to the posts table, you'll want to use external validation. Create a function called Model_Post::rule_has_valid_categories($submitted_categories, $post) that returns a boolean denoting whether or not the submitted categories are valid for this post.

Then, create the extra rule just before you try to save the post:

$extra_rules = Validation::factory(array('categories' => $submitted_categories))
    ->rule(
    'categories',
    'Model_Post::rule_has_valid_categories',
    array(':value', ':model')
);

try
{
    $post->save($extra_rules);
}
catch (ORM_Validation_Exception $e)
{
    // if categories rule failed, array will contain _external[categories] field
    print_r($e->errors('models')); 
}

You store the message in /application/messages/models/post/_external.php:

return array(

    'categories' => array(
        'Model_Post::rule_has_valid_categories' => 'Invalid categories'
    ),

);
webbiedave
  • 48,414
  • 8
  • 88
  • 101