From the form fields on the site, information always comes in the form of text, even if I indicate in the model

public function rules() { return [ [['field'], 'integer'], ]; } 

type conversion occurs only if done like this:

 public function behaviors() { 'typecast' => [ 'class' => AttributeTypecastBehavior::className(), 'attributeTypes' => [ 'field' => AttributeTypecastBehavior::TYPE_INTEGER, ], 'typecastAfterValidate' => true, 'typecastBeforeSave' => false, 'typecastAfterFind' => false, } 

so it should be, or am I doing something wrong? According to my logic, specifying in rules the type of system should lead field to type INTEGER, and also save in the database, but not, saves as text!

    2 answers 2

    In the framework of Yii2, it is logical to type in the validation rules using filter:

     public function rules() { return [ [['field'], 'filter', 'intval'], [['field'], 'integer'], ]; } 

    Then during validation before checking for a number, your value will be cast to int.

    • when saving, I get the Setting unknown property: yii \ validators \ FilterValidator :: 0, what's wrong? - Monitorkin pm
    • thanks, figured it out, it works - Monitorkin
     public function beforeValidate() { parent::beforeValidate(); $this->field = (int) $this->field; return true; } 

    http://php.net/manual/ru/language.types.type-juggling.php

    • thanks, it works - Monitorkin