Having troubles with custom validation in Yii2 basic project.
Controller:
$property = new Property();
$propertyDetails = new PropertyDetails();
$data = [
'property' => $property,
'propertyDetails' => $propertyDetails,
];
return $this->render('create-individual', $data);
Property model:
namespace app\models;
use Yii;
use app\models\PropertyDetails;
use app\models\Countries;
class Property extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['user_id', 'title', 'title_local', 'type_id', 'subtype_id', 'subtype_type_id', 'country_code', 'area', 'city', 'street', 'nr', 'geo_lat', 'geo_long', 'price', 'currency', 'deposit', 'comission'], 'required'],
[['user_id', 'type_id', 'subtype_id', 'subtype_type_id'], 'integer'],
[['geo_lat', 'geo_long', /*'price', */'deposit', 'comission'], 'number'],
[['title', 'title_local', 'city'], 'string', 'max' => 50],
[['area', 'street'], 'string', 'max' => 100],
[['nr'], 'string', 'max' => 5],
[['currency'], 'string', 'max' => 10],
];
}
}
PropertyDeatils:
namespace app\models;
use Yii;
class PropertyDetails extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['property_id', 'classification', 'bedrooms', 'baths', 'rooms', 'floor_area', 'floor_nr', 'floors_total', 'furnished', 'car_spaces'], 'required'],
[['property_id', 'classification', 'bedrooms', 'baths', 'rooms', 'floor_area', 'floor_nr', 'floors_total', 'furnished', 'car_spaces'], 'integer'],
['available_from', function ($attribute, $params, $validator) {
$this->addError($attribute, 'The token must contain letters or digits.');
}, 'skipOnError' => false, 'skipOnEmpty' => false],
];
}
}
This field in view
<?php $form = ActiveForm::begin(['options' =>['id' => 'property-submit-form', 'enctype' => 'multipart/form-data']]); ?>
<?= $form->field($propertyDetails, 'available_from', ['options' => ['class' => '']])
->input('text', ['placeholder' => 'DD.MM.YYYY'])
->label(false)
->error(false) ?>
<?= $form->errorSummary([$property, $propertyDetails]) ?>
<?php ActiveForm::end(); ?>
If i try to validate this field in ProperyDetails by making it required it’s working ok. But it won’t validate it via function.
The second problem:
If i try to make something like in PropertyDetails model:
[['rooms', 'bedrooms', 'baths''], 'required', 'when' => function($model) {
return $model->type_id == 1;
},'whenClient' => "
return $('#apartment').css('display') === 'block';
"],
it won’t even validate rules from Property model rules even i didn’t even change it though.
| Q | A
| ---------------- | —
| Yii version | 2.0.12
| PHP version | 7.1.9
| Operating system |Ubuntu 16.04