There is a form ( Model ) that has more than 1 validator per field. In theory, the validate() method should check with all validators and enter all the errors found in the _errors property, and not stop after the first error. This assumption logically follows from the fact that the getErrors() documentation shows an example, where a two-dimensional array is returned and the username attribute in the example has 2 errors at once. To return only the first values, there is the getFirstErrors() method, which just returns a one-dimensional array of one error per attribute. But it is not clear when all the same, getErrors() returns more than 1 error per attribute and how to achieve this if necessary?
Here is a test case. Create a new project Yii2 on the advanced template with the command composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-advanced testProject . Initialize with the init command. Add 2 files to it.
Test form in common/models/TestForm.php
<?php namespace common\models; use yii\base\Model; class TestForm extends Model { public $fullName; /** * @inheritdoc */ public function rules() { return [ ['fullName', 'required'], // ΠΠΎΠ»Π½ΠΎΠ΅ ΠΈΠΌΡ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ Π±ΡΡΡ ΠΏΡΡΡΡΠΌ ['fullName', 'string', 'min' => 5, 'max' => 100], // ΠΠΎΠ»Π½ΠΎΠ΅ ΠΈΠΌΡ Π΄ΠΎΠ»ΠΆΠ½ΠΎ Π±ΡΡΡ ΡΡΡΠΎΠΊΠΎΠΉ ΠΎΡ 5 Π΄ΠΎ 100 ΡΠΈΠΌΠ²ΠΎΠ»ΠΎΠ² ['fullName', 'match', 'pattern' => '/^\w+(?:\s+\w+)+$/u'], // ΠΠΎΠ»Π½ΠΎΠ΅ ΠΈΠΌΡ Π΄ΠΎΠ»ΠΆΠ½ΠΎ ΡΠΎΡΡΠΎΡΡΡ ΠΈΠ· 2+ ΡΠ»ΠΎΠ² ]; } } Test console controller to check in console/controllers/TestFormController.php
<?php namespace console\controllers; use common\models\TestForm; use Yii; use yii\console\Controller; class TestFormController extends Controller { public function actionIndex($fullName) { $form = new TestForm(); $form->fullName = $fullName; if ($form->validate()) { echo "Form validated successful\n"; } else { echo "Form validated with errors:\n\n"; var_dump($form->getErrors()); } } } Perform a test in the console:
yii test-form "asd" We get the result:
Form validated with errors: array(1) { ["fullName"]=> array(1) { [0]=> string(47) "Full Name should contain at least 5 characters." } } Although the passed "asd" parameter does not satisfy 2 validators at once: "string" and "match". In the documentation, I did not find anything on the fly about it.
validatemethod, which is responsible for clearing the previous errors. Try this:$form->validate(null, false). - Razzwan$form->validate()or$form->addError(). Now I will write the answer to the question. - gugglegum