嗨我有2个下拉列表:
<?= $form->field($model, 'Rel_User')->widget(Select2::classname(), [
'data' => ArrayHelper::map(UrUser::find()->orderby('Surname')->all(), 'Id', 'fullName'),
'language' => 'pl',
'options' => ['placeholder' => Yii::t('app', 'Wybierz użytkownika ...')],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'Rel_Category')->widget(Select2::classname(), [
'data' => ArrayHelper::map(SmUserCategory::find()->orderby('Name')->all(), 'Id', 'Name'),
'language' => 'pl',
'options' => ['placeholder' => Yii::t('app', 'Wybierz kategorię ...')],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
如果没有选择第二个,我想要其中一个是必需的。因此,如果用户不选择它们,则应在其中两个下显示消息,但如果用户选择一个,则应保存我的模型。 我尝试用规则做到这一点:
[['Rel_User'], 'required', 'whenClient' => "function (attribute, value) {return $('#banner-rel_category input[type=dropdown]:checked').val() == null}"],
[['Rel_Category'], 'required', 'whenClient' => "function (attribute, value) {return $('#banner-rel_user input[type=dropdown]:checked').val() == null}"],
但现在需要2个时间。我能做些什么呢? 我的动作是在ctrl中创建的
public function actionCreate() {
$model = new Banner();
$model->scenario='create';
if ($model->load(Yii::$app->request->post())) {
$model->File = UploadedFile::getInstance($model, 'File');
if ($model->save() && $model->upload() && $model->validate()) {
return $this->redirect(['view', 'id' => $model->Id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
我现在的规则:
public function rules() {
return [
[['Url'], 'required'],
[['File'], 'required', 'on' => 'create'],
[['Rel_User'], 'my_required'],
[['Rel_Category'], 'my_required'],
[['Views', 'Rel_User', 'Rel_Category', 'CreatedAt', 'UpdatedAt', 'IsDeleted', 'Id'], 'integer'],
[['Image', 'Url', 'Caption'], 'string', 'max' => 255],
[['Url'], 'match', 'pattern' => '/^(http(s?):\/\/)?(www\.)?[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$/'],
[['File'], 'file', 'extensions' => ['gif', 'jpg', 'png', 'jpeg', 'JPG', 'JPEG', 'PNG', 'GIF'], 'checkExtensionByMimeType' => false,],
[['CreatedAt', 'IsDeleted'], 'safe']
];
}
答案 0 :(得分:0)
在模型中使用自定义验证:
public function rules()
{
return [
[['Rel_User, Rel_Category'], 'my_required'],
];
}
public function my_required($attribute_name, $params)
{
if (empty($this->Rel_User) && empty($this->Rel_Category))
{
$this->addError($attribute_name, Yii::t('app', 'At least 1 of the field must be filled up properly'));
return false;
}
return true;
}