I’m new to yii2, I’m trying to send a request to the database, but it comes out that such columns cannot be null, although when checking through @var_dump I can see the sending data, what is the matter and how to fix it
—> Controller
public function actionSignup()
{
$model = new Signup();
if (isset($_POST['Signup'])) {
$model->attributes = Yii::$app->request->post('Signup');
if ($model->validate()) {
$model->signup();
# code...
}
}
return $this->render('signup', ['model'=>$model]);
—> View page
<?php
use yiiwidgetsActiveForm;
?>
<?php
$form = ActiveForm::begin(['class'=>'form-horizontal']);
?>
<?= $form->field($model,'email')->textInput(['autofocus'=>true]) ?>
<?= $form->field($model,'password')->passwordInput() ?>
<div>
<button type="submit" class="btn primary-btn">Submit</button>
</div>
<?php
ActiveForm::end();
?>
—> Model
class Signup extends Model
{
public $email;
public $password;
public function reles()
{
return [
[['email', 'password'], 'required'],
['email', 'email'],
['email', 'unique', 'targetClass'=>'appmodelsUser'],
['password', 'string', 'min'=>2,'max'=>10]
];
}
public function signup()
{
$user = new User();
$user->email = $this->email;
$user->password = $this->password;
return $user->save();
}
—> phpmyadmin database
namespace appmodels;
use yiidbActiveRecord;
class User extends ActiveRecord
{
}
2
Answers
Try this:
In Model
First of all, the method for attribute rules is called "rules" I don’t know if it’s a typo from you in the question or this is the problem; If there are no rules for user input data the returned values will be NULL, I have faced this issue before, I didn’t include a rules() method (or in your case it’s name is not correct) and the model returned null for attribute values. Your code have to be:
Technical note: normally, or based upon my understanding a password should have a minimum of 8 not 2 characters, if the password entered is only 2 characters it can be brute-forced in a second.
In Controller
As in @Serghei Leonenco’s Answer, Yii2 already provides some functions to use to handle post requests and so, so please stick to Yii2 functions it can enhance your app security
So in the actionSignup() method the code ought to be
In View
At last, in your view code it’s better to use Yii2 internal functions for Html buttons
Of course don’t forget to use yiihelpersHtml