0
votes

I am trying to validate a simple form in Yii2 framework. validation method on model is -

    /**
     * {@inheritdoc}
     */

    public function rules()
    {
        return array(
            array('name', 'required'),
            // ... other rules
        );
    }

When i try to make request it says -

array(1) { ["name"]=> array(1) { [0]=> string(21) "Name cannot be blank." } }

But the thing is i am sending name field in request ( POST ). But after providing name field , it gives an error.

If i do var_dump for request It shows me that name field is in there the request.

Here is the var_dump of request data and the validation error. -

array(1) { ["name"]=> string(6) "distro" } array(1) { ["name"]=> array(1) { [0]=> string(21) "Name cannot be blank." } }

Thank you in advance.

1
Can you add the code of your action in controller so we can see how are you setting/validating the data? - Michal HynĨica
try $model->name = Yii::$app->request->post("username"); before validate - Paritosh Mahale
can you attatch code of controller>action for better solution - Shringiraj Dewangan
You have to load the requested data to the model before validates by using $model->load(Yii::$app->request->post()) method. This method will help you to map the requested data to the model. - Shifrin

1 Answers

1
votes

If I correct understanding your question, your problem is in your name of input. In Yii2 ActiveRecord all data is in array of model name. for example:

Your models name is Users, when you using ActiveRecord your data must send like this to rules work on it:

{
    'Users' => {
        'username' => 'john_doe',
        'fullname' => 'John Doe',
    }
}

so change your html form input name to: model_name[field_name]

like this :

<input type="text" name="Users[username]">