Welcome Guest, Not a member yet? Register   Sign In
Datamapper get_rules on related tables
#1

[eluser]Dunmail[/eluser]
I have a set of get_rules that format fields depending on user preferences. They work fine when I call get() directly on the model but when fields from the table are pulled in via an include_related() call they don't get run.

Code:
//Here's the validation array within the Club class:
var $validation = array(
            'clubName' => array(
                'label' => 'Club Name',
                'get_rules' => array('format_name')
            )
        );

// So when I do the following, the get_rule is run
$c = new Club();

$c->get();

// When I do this, then the get_rule isn't run
$m = new Member();

$m->include_related('club', array('clubName'));

$m->get();

It looks like the rule is directly hooked in to the primary get() call. So how do I ensure that a get_rule (or similar) is invoked on a field no matter if it's retrieved directly or via a relation?
#2

[eluser]Dunmail[/eluser]
Found a solution. It may not be the ideal or recommended way though.

I extended the DataMapper class and put the formatting functions in the new class then had my DataMapper models extend the new class.

Code:
class DataMapperExt extends DataMapper {
    function _format_name($field){
        ...
    }
}

Then the club class does this
Code:
class Club extends DataMapperExt{
    var $validation = array(
            'club_name' => array(
                'label' => 'Given Name',
                'rules' => array('trim'),
                'get_rules' => array('format_name')
            ),
            'member_given_name' => array(
                'label' => 'Given Name',
                'rules' => array('trim'),
                'get_rules' => array('format_name')
            )
    );
}

Doing it this way lets all my models have access to the formatting functions, I just have to remember to name the fields correctly when accessed via a relation - see the second rule.
#3

[eluser]WanWizard[/eluser]
The best and most flexible way to share validation rules between models is to use an extension.

Load it (or autoload it), and make sure the method has a "rule_" prefix, so in this case "rule_format_name".

See http://datamapper.wanwizard.eu/pages/val...stom.Rules
#4

[eluser]Dunmail[/eluser]
Hmm. Tried that but must have being doing something wrong as I couldn't get it to work :-(
#5

[eluser]WanWizard[/eluser]
Can't judge unless you show some code... Wink




Theme © iAndrew 2016 - Forum software by © MyBB