答案 0 :(得分:1)
为了使其工作,我们需要different approach
,instead adding error when we are selecting
我们可以抛出错误when saving
,(因为添加java脚本有点难以及其客户端如此不安全)
只需将此code
添加到您的controller
和change fields according to need
。
public function onRelationManageAdd() {
$checked = \Input::get('checked');
$field = \Input::get('_relation_field');
$maximumAllowed = 2;
// i have used comment $field you need to replace it with your field
// this will be your hasMany relational field name
// also added condition to check selected id is more then 2
if($field == 'comments' && is_array($checked) && count($checked) > $maximumAllowed) {
// if selected id is more then 2 we add flash error and return blank array
\Flash::error('You Can Select Only 2 !');
return [];
}
// ADDITIONAL CHECK if you need more check you can add it here and return error
if($field == 'comments' && isset($this->params[0])) {
// currently editing record id.
$currentEditRecordId = $this->params[0];
$record = \October\Test\Models\Post::find($currentEditRecordId);
if($record && $record->comments->count() >= $maximumAllowed) {
\Flash::error('You Can Select Only 2 !');
return [];
}
}
// if everything is good then handle request by relation manger
//and return response
return $this->asExtension('RelationController')->onRelationManageAdd();
}
我添加了ADDITIONAL CHECK
,因为这会允许用户select 2 records per one time
,但是用户可以select 2 records multiple time
,但我们不允许这样做;)
您可以添加自己喜欢的custom validations
。
问题:第一次选择1条记录,然后选择另一条记录 - 解决方案
public function onRelationManageAdd() {
$checked = \Input::get('checked');
$field = \Input::get('_relation_field');
$maximumAllowed = 2;
$count = 0;
// i have used comment $field you need to replace it with your field
// this will be your hasMany relational field name
// also added condition to check selected id is more then 2
if($field == 'comments' && is_array($checked)) {
//$count += count($checked);
$count = $count + count($checked);
}
// ADDITIONAL CHECK if you need more check you can add it here and return error
if($field == 'comments' && isset($this->params[0])) {
// currently editing record id.
$currentEditRecordId = $this->params[0];
$record = \October\Test\Models\Post::find($currentEditRecordId);
if($record) {
$count = $count + $record->comments->count();
}
}
if($count > $maximumAllowed) {
// if selected id is more then 2 we add flash error and return blank array
\Flash::error('You Can Select Only 2 !');
return [];
}
// if everything is good then handle request by relation manger
//and return response
return $this->asExtension('RelationController')->onRelationManageAdd();
}
信息:您可以将此relational field in update context
添加为用户adding new record
作为当前记录we don't have information for current record
的时间is not saved yet
,relation count
第二次检查和validation will fail
。
以避免此问题您可以为该字段添加更新上下文,该字段仅在update
中可用。
banner:
label: Banner
oc.commentPosition: ''
mode: file
span: auto
type: mediafinder
context: update <------ add this option
现在此字段仅在用户保存记录时显示。我们现在对验证很满意。
如果您收到任何错误,请发表评论。