0

function rules not applied in my code, and I did the same code in the loginFrom model but it worked well ! here is my model

<?php

namespace backend\models;
use Yii;
use yii\base\Model;
class Year extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            [['Current_Year', 'Date', 'Description'], 'required'],
        ];
    }
    public static function tableName()
    {
        return 'year';
    }

    public function attributeLabels()
    {
        return [
            'YearId' => 'Year ID',
            'Theme' => 'Theme',
            'Current_Year' => 'Current  Year',
            'Date' => 'Date',
            'Description' => 'Description',
        ];
    }

}
shrouk mansour
  • 381
  • 3
  • 16
  • What are you trying to do with this model? At what point are you calling some code and expecting the rules to do anything? – Jap Mul Apr 21 '17 at 13:34
  • In my view page, I want the user th enter the data of a new year
    Enter the name

    this is for only one attribute but not working
    – shrouk mansour Apr 21 '17 at 13:36
  • Can you add this code to your question, as it is extremely relevant to why your code is not working. Thanks! – Joe Miller Apr 21 '17 at 16:06
  • You should use all lowercase names for your columns. This will help prevent typos in the future when referencing the columns. -- Also, please show your view code and the controller action. -- It looks like your form is not correct and you should use the Yii2 ActiveForm so it generates the form input values and IDs accordingly. – Wade Apr 21 '17 at 17:29

1 Answers1

0

Your problem is not that your validation is not working, but that the data is not correct when received by the server. It will not have the correct names to enable Yii to match the model attributes to the required rules. Your form should instead look something like this;

$form = ActiveForm::begin();
echo $form->field($model, 'name')->textInput();
$form = ActiveForm::end();

where $model is an instance of your Year class.

This will use Yii to generate all the matching names of the fields, and will then be able to match the validation rules to the attributes. You will find that the name of your field will be something like Year['name'], and Yii can find the validation rules for that attribute.

Joe Miller
  • 3,843
  • 1
  • 23
  • 38