V
V
Vladimir2017-02-01 19:24:42
Yii
Vladimir, 2017-02-01 19:24:42

Why is yii2 validation not working?

Good day! There is a form for adding information to the site. To be more precise, there are three of them similar (slightly different fields). Two forms work out validation perfectly, and the third does not respond.
Here is the third form code:
(_form.php)

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<div class="row">
    <div class="col-sm-6">
        <?= $form->field($model, 'type_of_sales')->dropDownList(['0' => 'Продать', '1' => 'Аренда', '2' => 'Долгосрочная аренда',]) ?>
        <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
        <?= $form->field($model, 'area')->textInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'city')->dropDownList($city) ?>
        <?= $form->field($model, 'district')->dropDownList(\yii\helpers\ArrayHelper::map(\app\modules\admin\models\Districts::find()->all(), 'title', 'title')) ?>
        <?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'land_type')->dropDownList($land_type) ?>
    </div>
    <div class="col-sm-6">
        <?= $form->field($model, 'phone')->textInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'communicationArr')->checkboxList(['Свет' => 'Свет', 'Газ' => 'Газ', 'Вода' => 'Вода']) ?>
        <?= $form->field($model, 'contact_name')->textInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'vip')->radioList(['0' => 'Нет', '1' => 'Да',]) ?>
        <div class="exchange_trigger">
            <?= $form->field($model, 'exchange')->radioList(['1' => 'Да', '0' => 'Нет',]) ?>
        </div>
        <?= $form->field($model, 'exchange_field', ['options' => ['id' => 'rent_block']])->textInput(['maxlength' => true, 'placeholder' => 'Например: гараж, дачу, 2-х комнатную квартиру',])->label(false) ?>
        <?= $form->field($model, 'price', ['options' => ['class' => 'col-sm-8 row', 'id' => 'price_block']])->textInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'currency', ['options' => ['class' => 'col-sm-4 row pull-right', 'id' => 'currency_block']])->dropDownList(['uah' => 'UAH', 'usd' => 'USD', 'eur' => 'EUR']) ?>
        <div class="col-sm-12">
            <?= $form->field($model, 'gallery[]', ['options' => ['class' => 'row']])->fileInput(['multiple' => true]) ?>
        </div>
    </div>
    <div class="col-sm-12">
        <div class="form-group col-sm-6">
            <?= $form->field($model, 'reCaptcha')->widget(
                \himiklab\yii2\recaptcha\ReCaptcha::className(),
                ['siteKey' => 'бла-бла-бла']
            )->label(false)?>
        </div>
        <div class="col-sm-6">
            <?= Html::submitButton($model->isNewRecord ? 'Добавить!' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success center-block' : 'btn btn-primary center-block']) ?>
        </div>
    </div>
</div>
<?php ActiveForm::end(); ?>

(LandParts - Model)
class LandParts extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */

  //public $image;
  public $gallery;
  public $reCaptcha;

    public static function tableName()
    {
        return 'land_parts';
    }

    public function scenarios()
    {
        return [
            $this::SCENARIO_DEFAULT => [
                'communicationArr'
            ],
        ];
    }

    public function behaviors(){
        return [
            'gallery' => [
                'class' => 'rico\yii2images\behaviors\ImageBehave',
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['description', 'area', 'city', 'address', 'phone', 'contact_name', 'price', 'land_type', 'type_of_sales'], 'required'],
            [['description', 'vip', 'available', 'new', 'sale', 'currency', 'communication', 'exchange_field'], 'string'],
            [['area', 'land_document', 'hot', 'exchange'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['title', 'price'], 'string', 'max' => 40],
            [['city'], 'string', 'max' => 50],
            [['address'], 'string', 'max' => 80],
            [['phone', 'contact_name'], 'string', 'max' => 25],
            [['realtors'], 'string', 'max' => 255],
            [['land_type'], 'string', 'max' => 100],
            [['gallery'], 'file', 'extensions' => 'png, jpg', 'maxFiles' => 4],
            [['city'], 'exist', 'skipOnError' => true, 'targetClass' => City::className(), 'targetAttribute' => ['city' => 'city_name']],
            [['district'], 'exist', 'skipOnError' => true, 'targetClass' => Districts::className(), 'targetAttribute' => ['district' => 'title']],
      [['land_type'], 'exist', 'skipOnError' => true, 'targetClass' => LandPartsType::className(), 'targetAttribute' => ['land_type' => 'title']],
      [[], \himiklab\yii2\recaptcha\ReCaptchaValidator::className(), 'secret' => 'бзззз'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Заголовок',
            'description' => 'Описание',
            'area' => 'Площадь',
            'distance_from_city' => 'Дистанция от города',
            'land_document' => 'Акт на землю',
            'communication' => 'Коммуникации',
            'city' => 'Город',
            'district' => 'Город',
            'address' => 'Адрес',
            'vip' => 'VIP Статус',
            'available' => 'Показывать',
            'phone' => 'Номер телефона',
            'realtors' => 'Риэлторы',
            'hot' => 'Горячее предложение',
            'exchange' => 'Обменять на:',
            'contact_name' => 'Ваше имя',
            'price' => 'Цена',
            'new' => 'Новый',
            'created_at' => 'Дата создания',
            'sale' => 'Продан',
      'land_type' => 'Тип земли',
      'gallery' => 'Картинки',
      'currency' => 'Валюта',
            'type_of_sales' => 'Я хочу',
            'communicationArr' => 'Коммуникации',
        ];
    }

    /**
     * Work with SET field in DB
     */
    public function getCommunicationArr()
    {
        return explode(',', $this->communication);
    }

    public function setCommunicationArr($value)
    {
        $this->communication = is_array($value) ? implode(',', $value) : '';
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCity0()
    {
        return $this->hasOne(City::className(), ['city_name' => 'city'])->inverseOf('landParts');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getLandType()
    {
        return $this->hasOne(LandPartsType::className(), ['title' => 'land_type'])->inverseOf('landParts');
  }


    public function upload()
    {
        if($this->validate()){
            $path = 'images/store/' . $this->image->baseName . '.' . $this->image->extension;
            $this->image->saveAs($path);
            $this->attachImage($path);
            @unlink($path);
            return true;
        } else {
            return false;
        }
    }

  public function uploadGallery()
    {
    if($this->validate()){
      foreach ($this->gallery as $file){
        $path = 'images/store/' . $file->baseName . '.' . $file->extension;
        $file->saveAs($path);
        $this->attachImage($path);
        @unlink($path);
      }
    return true;
    } else {
      return false;
    }
  }
}

(Controller actionCreate)
public function actionCreate()
{
    $this->layout = '/gold';

    $model = new LandParts();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
    $model->gallery = UploadedFile::getInstances($model, 'gallery');
    if ($model->gallery)
      $model->uploadGallery();
        Yii::$app->session->setFlash('success', 'Ваше объявление пройдет предварительную модерацию и будет добавлено на сайт!');
        return $this->refresh();
    } else {
        return $this->render('create', compact('model'));
    }
}

This is a standard yii2 validation when you click on a field and then reset the focus, and it highlights the field in red or green for you. Tell me, what could it be? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Fedorov, 2017-02-07
@MasterGerold

the problem is in your scenarios method, there is one active attribute specified for the default scenario. Accordingly, all other attributes are not active, and therefore are not validated on the client.

V
vism, 2017-02-01
@vism

If the forms are identical, there may be a jamb in js on the page, therefore events and validation do not work

A
AlxMrz, 2017-02-01
@AlxMrz

Too little information. Bring your code from the rules() method, where you set the validation rules, as well as a code fragment, where you display the field in the template

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question