S
S
Sergey2016-02-04 15:23:43
Yii
Sergey, 2016-02-04 15:23:43

Is one of the two fields required Yii2?

2606788f107b4d7d9dbbbc321974f7d8.jpg
Hello! The question is there are two fields phone and phone-other how to make one of the two fields required?
view

<?= $form->field($model, 'phone')->widget(MaskedInput::className(), [ 'mask' => ['+38 (999) 999-99-99'],  'options' =>['placeholder' => 'Мобильный номер телефона']])->label('Телефон *')->hint('для подтверждения и статусов заказа') ?>
          
<?= $form->field($model, 'phone_other')->textInput(['placeholder' => 'Другой номер телефона'])->label('Доп. телефон *')->hint('для подтверждения заказа') ?>

model
[['phone', 'phone_other'], 'required', 'when' => function ($model) {
   $validate = empty($model->phone) && empty($model->phone_other);
    if ($validate) { return false; }
    return true;
    }, 'whenClient' => "function (attribute, value) {
                return $('#order-phone').val() == '' && $('#order-phone_other').val() == '';
    }", 'message' => 'Необходимо заполнить хотя бы одно из полей "Телефон" или "Доп. Телефон"'],

Validation works on submit. But when the field is onchange, then the validation takes place only in the field that has changed.
How to make that two fields would change at onchange of at least one field?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
S
Sergey, 2016-02-04
@spy_reality

Decided so.

[['phone', 'phone_other'], 'required', 'when' => function ($model) {
    $validate = empty($model->phone) && empty($model->phone_other);
    if ($validate) { return false; }
    return true;
    }, 'whenClient' => "function (attribute, value) {
    if($('#order-phone').val() == '' && $('#order-phone_other').val() == ''){
    $('.field-order-phone, .field-order-phone_other').addClass( 'has-error' ).find('.help-block-error').text( 'Необходимо заполнить хотя бы одно из полей «Телефон» или «Доп. Телефон»');
    return true;
    } else { 
    $('.field-order-phone, .field-order-phone_other').removeClass( 'has-error' ).find('.help-block-error').text('');
    return false;
    }
   }", 'message' => 'Необходимо заполнить хотя бы одно из полей «Телефон» или «Доп. Телефон»'],

The implementation is not the best, maybe someone knows how to do it right.

J
jacksparrow, 2016-02-04
@jacksparrow

Logically, make the first field mandatory. The second is optional.
And so, one of the first links Google

public function rules()
{
    return array(
        // array('username, email', 'required'), // Remove these fields from required!!
        array('email', 'email'),
        array('username, email', 'my_required'), // do it below any validation of username and email field
    );
}

public function my_required($attribute_name, $params)
{
    if (empty($this->username)
            && empty($this->email)
    ) {
        $this->addError($attribute_name, Yii::t('user', 'At least 1 of the field must be filled up properly'));

        return false;
    }

    return true;
}

S
sokollondon, 2021-03-16
@sokollondon

I will keep in the answers a simple example of validation by two fields =)

public function rules()
{
    return [
        [['phone', 'phone_other'], 'required', 'when' => function($model) {
            return (!$model->phone && !$model->phone_other);
        },'whenClient' => 'function(){return false;}',
        /*'whenClient' => 'function (attr, value) {
            return $("#MODEL-phone").val() == "" && $("#MODEL-phone_other").val() == "";
        }', 'message' => 'Заполните "Телефон" или "Доп. Телефон"'*/],
        //...
    ];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question