问题
I have the following relation with the user model
public $belongsTo = [
'user' => [
'Rainlab\User\Models\User',
'key' => 'user_id',
'order' => 'name asc'
]
];
config_relation.yaml
user:
label: Usuários
view:
form: $/rainlab/user/models/user/fields.yaml
toolbarButtons: create|link
manage:
showSearch: true
showCheckBoxes: true
recordsPerPage: 10
list: $/rainlab/user/models/user/columns.yaml
form: $/rainlab/user/models/user/fields.yaml
I am doing the validation on the user field, but it is not working, even though I have already selected the user it continues informing that I need to select the user
/**
* @var array Validation rules
*/
public $rules = [
'user' => 'required'
];
回答1:
Yes, I can Understand your problem. this will occur only when you are going to add new record.
It will work perfectly for existing record. as for existing record data is persisted in database so we can represent a working record and then we can fire relational validation on it.
but for new record there is no ID means record it self is not saved in database so there will be no relation with that relational field so we never know this field has some value attached to it or not and validation will gonna fail all the time.
so no matter how much record you add, it will show ERROR each time that "please select user".
October CMS use differ binding you can see you can add users without saving current record. as that data is stored in intermediate table so after record is created that relation data will be transferred to created record because now it has it's own ID and persisted in database.
so for solution you need add validation manually inside that model, with
differed binding scope.
First remove field user from rules
/**
* @var array Validation rules
*/
public $rules = [
'user' => 'required' <-- Remove this
];
Now we will do manual validation
Add this
codeto yourmodel
public function beforeValidate() {
// we need to check record is created or not
if($this->id == NULL) {
// CREATE CASE
// we need to use differ binding scope as this record is not saved yet.
if($this->user()->withDeferred(post('_session_key'))->count() == 0) {
throw new \ValidationException(['user' => 'We need User !']);
}
}
else {
// UPDATE CASE
// now record is created so we dont need differ binding
if($this->user()->count() == 0) {
throw new \ValidationException(['user' => 'We need User !']);
}
}
}
Now Validation can work for both case and you can add different validation for different cases.
Now Validation will work properly.
if you still find issue please comment.
来源:https://stackoverflow.com/questions/48502709/octobercms-validation-relation-user