S
S
Sergey Beloventsev2017-08-17 21:04:51
Yii
Sergey Beloventsev, 2017-08-17 21:04:51

Why doesn't self-validation pass?

I tried to organize my own validation here is the model

class SearchForm extends Model
{
    public $ingredients;

    public function rules(){
        return[
            ['ingredients', function ($attribute, $params) {
                if (count($this->attribute)<2) {
                    $this->addError($attribute, 'Выберите больше ингредиентов.');
                }
                if (count($this->attribute)>5) {
                    $this->addError($attribute, 'Нельзя выбрать больше 5 ингредиентов.');
                }
            }]
        ];
    }
}

controller
public function actionIndexSite()
    {
        $model=new SearchForm();
        return $this->render('indexsite', [
            'model'         =>  $model
        ]);
    }

part of a species
<?php $form = ActiveForm::begin(); ?>
        <?php echo $form->field($model, 'ingredients')->widget(Select2::classname(), [
                'language' => 'en',
                'data' => $ingredients,
                'options' => ['multiple' => true, 'placeholder' => 'Select ingredients'],
            ]); ?>
        <div class="form-group">
            <div class="col-lg-offset-1 col-lg-11">
                <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
            </div>
        </div>
        <?php ActiveForm::end(); ?>

this is the array i get
SearchForm 	[
    'ingredients' => [
        0 => '1'
    ]
]

validation passes and the page is reloaded, why don't you tell me and how to do it right.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Timofeev, 2017-08-18
@Sergalas

validation passes and the page reloads

Where is it $model-load()? You not only do not start validation, in general the data is not loaded into the model.

D
Dmitry, 2017-08-17
@slo_nik

Good evening.
First, try to inherit from the main model, Ingridients, if I understand correctly.

M
mitaichik, 2017-08-17
@mitaichik

Because you need to write $this->$attribute in the validator. And your validation code, IMHO, in general, the exception should be thrown out, strange if not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question