Roby Sottini
Roby Sottini

Reputation: 2265

Yii2: How to avoid required fields in a view?

I have a view about holidays where a user uses a form to choose a place to travel and a hotel. It has two models: HolidaysPlaces and HolidaysHotels.

The user have to fill the form in this order using the view:

  1. The user completes the fields called Place and City (related with the HolidaysPlaces model).
  2. The user checked a checkbox if he/she wants to choose a hotel. It able a field called Hotel (related with HolidaysHotels model).
  3. The user completes that field.
  4. The user press a Create button.
  5. The controller receives and saves both models.

But the problem is when the user doesn't select the checkbox (number 2 of the list): The Hotel fieldis still required (with the red asterisk as defined in its model file). So the Create button doesn't work in this case.

How can I disabled the required feature?

enter image description here

Upvotes: 1

Views: 759

Answers (3)

Roby Sottini
Roby Sottini

Reputation: 2265

The easiest way to solve it is to send the model with empty strings. Then the controller checks if the strings are empty. If so, the model is not saved. Else, it is saved.

It was the only way that works for me.

Upvotes: 0

Kumar V
Kumar V

Reputation: 8830

You can add some condition based validation in your model rules. Here is the snippet for both client and server validation. You can many conditions inside the function block.

['field-1', 'required', 'when' => function ($model) {
    return $model->check_box == '1';
}, 'whenClient' => "function (attribute, value) {
    return $('#checkbox-id').is(':checked') ';
}"],

Upvotes: 0

mrateb
mrateb

Reputation: 2509

Add a scenario for this case in your HolidaysHotels model, and include only the fields that you want checked.

Example: If you have 3 fields name, date and age that are required, create a scenario for two only, and set the scenario in the controller. Only those two fields will be checked.

In model:

public function scenarios(){
$scenarios = parent::scenarios();
$scenarios['create'] = ['name', 'date'];
return $scenarios;
}

In controller:

$holiday = new HolidayHotels();
$holiday->scenario = 'create';

To know more about scenarios: http://www.yiiframework.com/doc-2.0/guide-structure-models.html#scenarios

Upvotes: 2

Related Questions