Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

if ($post->categories->find_all())
{
   //blablabla
}

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'
    ),

);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top