yii2yii2-advanced-appyii-validation

Required either one filed in Yii2 ActiveForm


I have a form Message In which there are 2 fields message and file

I want the validator to validate either one of them field as required

Here is what i have done until now but its not working

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;
}

Here is the code of my form

<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>

I also tried to use this but it didnt work as well

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);
        }],
    ];
}

I have also tried using inline validation like this

['file', function ($attribute,$model) {
        if (empty($model->message)) {
            $this->addError($attribute, 'Form must contain a file or message.');
        }
    }],

But that did not work out either...


Solution

  • Below works perfectly for me:

                ['clientGroupId', 'required', 'when' => function($model) {
                    return empty($model->clientId);
                }, 'message' => 'Client group or client selection is required'],