Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

[RFC] Validation of HABTM associations #2859

Closed
biesbjerg opened this Issue · 9 comments

5 participants

@biesbjerg

In CakePHP 2x it's not possible to have validation rules/errors for HABTM associations without hacks (Changing data format in Controller::beforeRender(), Model::beforeValidate() etc.).

An example:
Course hasAndBelongsToMany Lecturers
When adding a course it is required to associate at least one Lecturer.

I was curious if it is being considered to be addressed in 3x since I couldn't see anything about it in the roadmap?

@markstory markstory added the RFC label
@markstory markstory added this to the 3.0.0 milestone
@markstory
Owner

I don't think this is something we've built in so far. I can see how it would be handy though.

@lorenzo
Owner

It is possible in 3.x, your validation rules can be applied to any properties, including those that represent association data.

@lorenzo lorenzo closed this
@josegonzalez
Collaborator

@lorenzo I think he means something like "will associated models always have their related validation rules run", not "can I write a validation rule for an array of associated data"

@lorenzo
Owner

@lorenzo I think he means something like "will associated models always have their related validation rules run", not "can I write a validation rule for an array of associated data"

@biesbjerg did you mean that? ^^

The answer to that is: the data will be there if you load it, just like in 2.x

@AD7six
Collaborator

I read this as a request to have the described validation rule available in cake, and errors displayed without userland solutions. I.e. validate model has N whatevers -> habtm select error "please select more whatevers".

@biesbjerg

Let me try to explain again.

If you have a form that adds a Course with the following code:

(Course HABTM Lecturer)

$this->Form->create('Course');
$this->Form->input('Lecturer.Lecturer', array(
    'type' => 'select', 
    'multiple' => 'multiple'
));
$this->Form->end();

There is no way to tell CakePHP in 2.x that the user must select at least 1 Lecturer for the Course (for example).

Hope it's clearer now!

@biesbjerg

@AD7six Spot on! :-)

@lorenzo
Owner

Then, it is definitely possible to do it in 3.x. Associations are just another property. Maybe @markstory can say more on whether validation errors for a property that is also an entity will be displayed in the form helper

@markstory
Owner

Validation errors in forms are fetched by walking the entity chain to the leaf entity. From the leaf entity errors are fetched with the errors() method. So if you have errors accessible on a property path FormHelper should be able to read them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.