0
votes

I have two models that we're going to name Model and RelatedModel. Model has many RelatedModel. So if I add foreign key validation on validation array like:

public $validate = array(
'foreignKey' => array(
            'rule' => 'numeric',
            'required' => true,
            'message' => 'The id of relatedmodel should be a number'
        )
)

After I create a add() function to save new registers and in this function I use saveAssociated with validation true, this one fails throwing an error 'The id of relatedmodel should be a number'.

I'm debugging the code and saveAssociated checks validation of both models at the same time and before save Model.

Is this an issue?

I think what this function should do is to validate Model, save it, add foreignKey of RelatedModel and then validate it before save.

2

2 Answers

1
votes

I came into this issue only recently. It's not an issue, saveAssociated() is designed to work this way unfortunately.

What you can do is alter the required => true on the fly using the model validator. Check out the book for more information.

http://book.cakephp.org/2.0/en/models/data-validation.html#dynamically-change-validation-rules

0
votes

This is working as would be expected with your given rule. required in Cake means it expects the value of foreignKey to be set in the save data prior to saving. All the validation will happen before Cake saves the data (and therefore before foreignKey is generated).

You shouldn't need to validate that it is numeric if you are allowing Cake to generate this for you behind the scenes. If you want to check that it is being passed in the data for an UPDATE you could modify the required to be only for an update like this:-

public $validate = array(
    'foreignKey' => array(
        'rule' => 'numeric',
        'required' => 'update',
        'message' => 'The id of relatedmodel should be a number'
    )
)

Personally I wouldn't bother validating foreign keys unless a user is setting them rather than Cake.

Update:

To validate the foreignKey if it exists in a form submission you can drop the required option from the validation rule:-

public $validate = array(
    'foreignKey' => array(
        'rule' => 'numeric',
        'message' => 'The id of relatedmodel should be a number'
    )
);

This will allow you to pass data where the foreignKey is not present without throwing a validation error whilst validating it if it is.