我有一个表单numpy
其中有2个字段Message
和message
我希望验证器根据需要验证其中一个字段
这是我到目前为止所做的事情,但它不起作用
file
以下是我的表格代码
public function rules()
{
return [
[['sender_id', 'receiver_id'], 'integer'],
[['message'], 'string'],
[['message','file'],'my_required'],
[['is_delivered', 'is_notified', 'is_deleted', 'is_group'], 'boolean'],
[['created_date', 'updated_date'], 'safe'],
[['image'], 'string', 'max' => 500],
[['file'], 'file', 'extensions'=>'jpg, gif, png, pdf'],
];
}
public function my_required($attribute_name, $params)
{
if (empty($this->file)
&& empty($this->message)
) {
$this->addError($attribute_name, Yii::t('user', 'At least 1 of the field must be filled up properly'));
return false;
}
return true;
}
我也尝试使用它,但它也不起作用
<div class="row">
<p>
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data','id' => 'message-form']]); ?>
<div class="form-group col-xs-3 col-lg-3">
<?= $form->field($model, 'message')->textarea(['rows' => 6]) ?>
</div>
<div class="form-group col-xs-3 col-lg-3">
<?= $form->field($model, 'file')->fileInput() ?>
<?= $form->field($model, 'keys')->hiddenInput()->label(false); ?>
<div class="form-group">
<?= Html::submitButton('Send',['class' => 'btn btn-danger','data-placement'=>'right','id'=>'sendMessage']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</p>
</div>
我也尝试过像这样的内联验证
public function rules()
{
return [
[['sender_id', 'receiver_id'], 'integer'],
[['message'], 'string'],
[['is_delivered', 'is_notified', 'is_deleted', 'is_group'], 'boolean'],
[['created_date', 'updated_date'], 'safe'],
[['image'], 'string', 'max' => 500],
[['file'], 'file', 'extensions'=>'jpg, gif, png, pdf'],
['file', 'required', 'when' => function($model) {
return empty($model->message);
}],
];
}
但这也没有成功......
答案 0 :(得分:1)
以下对我来说非常合适:
['clientGroupId', 'required', 'when' => function($model) {
return empty($model->clientId);
}, 'message' => 'Client group or client selection is required'],