title: Integrity constraint violation – yii\db\IntegrityException Yii2
body: <p>When I signup and input data username, email and password. Field username is null, i don't know why. And then when I input again data username, email and password the result is error. The description error can see in the picture. </p>
  
  <p>Code for models/User.php : </p>
  
  <pre><code>&lt;?php
  
  namespace app\models;
  
  use Yii;
  use yii\web\IdentityInterface;
  use yii\db\ActiveRecord;
  use yii\behaviors\TimestampBehavior;
  
  class User extends ActiveRecord implements IdentityInterface
  {
      const STATUS_DELETED = 0;
      const STATUS_ACTIVE = 10;
  
      public $id;
      public $username;
      public $password;
      public $authKey;
      public $accessToken;
  
      public static function tableName()
      {
          return '{{%user}}';
      }
  
      public function behaviors()
      {
          return
              [
                  TimestampBehavior::className(),     
              ];
      }
  
      public function actionLogin()
      {
          if (!\Yii::$app-&gt;user-&gt;isGuest) {
              return $this-&gt;goHome();
          }
  
          $model = new LoginForm();
          if ($model-&gt;load(Yii::$app-&gt;request-&gt;post()) &amp;&amp; $model-&gt;login()) {
              return $this-&gt;goBack();
          }
          return $this-&gt;render('login', [
              'model' =&gt; $model,
          ]);
      }
  
      public function actionLogout()
      {
          Yii::$app-&gt;user-&gt;logout();
  
          return $this-&gt;goHome();
      }
  
      public function rules()
      {
          return 
          [
              ['status', 'default', 'value' =&gt; self::STATUS_ACTIVE],
              ['status', 'in', 'range' =&gt; [self::STATUS_ACTIVE, self::STATUS_DELETED]],
          ];
      }
  
      /**
      private static $users = [
          '100' =&gt; [
              'id' =&gt; '100',
              'username' =&gt; 'admin',
              'password' =&gt; 'admin',
              'authKey' =&gt; 'test100key',
              'accessToken' =&gt; '100-token',
          ],
          '101' =&gt; [
              'id' =&gt; '101',
              'username' =&gt; 'demo',
              'password' =&gt; 'demo',
              'authKey' =&gt; 'test101key',
              'accessToken' =&gt; '101-token',
          ],
      ]; */
  
      /**
       * @inheritdoc
       */
      public static function findIdentity($id)
      {
          return static::findOne(['id' =&gt; $id, 'status' =&gt; self::STATUS_ACTIVE]);
      }
  
      /**
       * @inheritdoc
       */
      public static function findIdentityByAccessToken($token, $type = null)
      {
      }
  
      /**
       * Finds user by username
       *
       * @param  string      $username
       * @return static|null
       */
      public static function findByUsername($username)
      {
          return static::findOne(['username' =&gt; $username, 'status' =&gt; self::STATUS_ACTIVE]);
      }
  
      /**
       * @inheritdoc
       */
      public function getId()
      {
          return $this-&gt;getPrimaryKey();
      }
  
      /**
       * @inheritdoc
       */
      public function getAuthKey()
      {
          return $this-&gt;auth_key;
      }
  
      /**
       * @inheritdoc
       */
      public function validateAuthKey($authKey)
      {
          return $this-&gt;getAuthKey() === $authKey;
      }
  
      /**
       * Validates password
       *
       * @param  string  $password password to validate
       * @return boolean if password provided is valid for current user
       */
      public function validatePassword($password)
      {
          return Yii::$app-&gt;security-&gt;validatePassword($password, $this-&gt;password_hash);
      }
  
      public function generatePasswordResetToken()
      {
          $this-&gt;password_reset_token = Yii::$app-&gt;security-&gt;generateRandomString() . '_' . time();
      }
  
      public function removePasswordResetToken()
      {
          $this-&gt;password_reset_token = null;
      }
  
      public function setPassword($password)
      {
          $this-&gt;password_hash = Yii::$app-&gt;security-&gt;generatePasswordHash($password);
      }
  
      public function generateAuthKey()
      {
          $this-&gt;auth_key = Yii::$app-&gt;security-&gt;generateRandomString(); 
      }
  }
  </code></pre>
  
  <p>Code for models/SignupForm.php :</p>
  
  <pre><code>&lt;?php
  namespace app\models;
  use app\models\User;
  use yii\base\Model;
  use Yii;
  
  class SignupForm extends Model
  {
      public $username;
      public $email;
      public $password;
      public function rules()
      {
          return 
          [
              ['username', 'filter', 'filter' =&gt; 'trim'],
              ['username', 'required'],
              ['username', 'unique', 'targetClass' =&gt; '\app\models\User', 'message' =&gt; 'This username has already been
             taken.'],
              ['username', 'string', 'min' =&gt; 2, 'max' =&gt; 255],
              ['email', 'filter', 'filter' =&gt; 'trim'],
              ['email', 'required'],
              ['email', 'email'],
              ['email', 'string', 'max' =&gt; 255],
              ['email', 'unique', 'targetClass' =&gt; '\app\models\User', 'message' =&gt; 'This email address has already
              been taken'],
              ['password', 'required'],
              ['password', 'string', 'min' =&gt; 6],
          ];
      }
  
      public function signup()
      {
          if ($this-&gt;validate())
          {
              $user = new user();
              $user-&gt;username = $this-&gt;username;
              $user-&gt;email = $this-&gt;email;
              $user-&gt;setPassword($this-&gt;password);
              $user-&gt;generateAuthKey();
              if ($user-&gt;save())
              {
                  return $user;
              }
          }
          return null;
      }
  }
  </code></pre>
  
  <p>Code controllers/siteController.php :</p>
  
  <pre><code>&lt;?php
  
  namespace app\controllers;
  
  use Yii;
  use yii\filters\AccessControl;
  use yii\web\Controller;
  use yii\filters\VerbFilter;
  use app\models\LoginForm;
  use app\models\ContactForm;
  use app\components\AuthHandler;
  use app\models\UserSocialMedia;
  use app\models\User;
  use app\helpers\Url;
  
  
  
  class SiteController extends Controller
  {
      public function behaviors()
      {
          return [
              'access' =&gt; [
                  'class' =&gt; AccessControl::className(),
                  'only' =&gt; ['logout'],
                  'rules' =&gt; [
                      [
                          'actions' =&gt; ['logout'],
                          'allow' =&gt; true,
                          'roles' =&gt; ['@'],
                      ],
                  ],
              ],
              'verbs' =&gt; [
                  'class' =&gt; VerbFilter::className(),
                  'actions' =&gt; [
                      'logout' =&gt; ['post'],
                  ],
              ],
          ];
      }
  
      public function actions()
      {
          return [
              'error' =&gt; [
                  'class' =&gt; 'yii\web\ErrorAction',
              ],
              'captcha' =&gt; [
                  'class' =&gt; 'yii\captcha\CaptchaAction',
                  'fixedVerifyCode' =&gt; YII_ENV ? 'testme' : null,
              ],
              'auth' =&gt; [
                  'class' =&gt; 'yii\authclient\AuthAction',
                  'successCallback' =&gt; [$this, 'successCallback'],
              ],
          ];
      }
  
      public function successCallback($client)
      {
          // call safeAttributes method for properly format data
          $attributes = $this-&gt;safeAttributes($client);
      }
  
      public function safeAttributes($client)
      {
          // get user data from client
          $attributes = $client-&gt;getUserAttributes();
  
          // set default value
          $safe_attributes = [
              'social_media' =&gt; '',
              'id' =&gt; '',
              'username' =&gt; '',
              'name' =&gt; '',
              'email' =&gt; '',
          ];
  
              // get value from user attributes base on social media 
              if ($client instanceof \yii\autclient\client\Facebook)
              {
                  $safe_attributes = [
                      'social_media' =&gt; 'facebook',
                      'id' =&gt; $attributes['id'],
                      'username' =&gt; $attributes['email'],
                      'name' =&gt; $attributes['name'],
                      'email' =&gt; $attributes['email'],
                  ];
              }
              else if ($client instanceof \yii\autclient\client\Google)
              {
                  $safe_attributes = [
                      'social_media' =&gt; 'google',
                      'id' =&gt; $attributes['id'],
                      'username' =&gt; $attributes['emails'] ['0'] ['value'],
                      'name' =&gt; $attributes['displayName'],
                      'email' =&gt; $attributes['emails'] ['0'] ['value'],
                  ];
              }  
              else if ($client instanceof \yii\autclient\client\Twitter)
              {
                  $safe_attributes = [
                      'social_media' =&gt; 'twitter',
                      'id' =&gt; $attributes['id'],
                      'username' =&gt; $attributes['screen_name'],
                      'name' =&gt; $attributes['name'],
                      'email' =&gt; '-',
                  ];
              }  
              else if ($client instanceof \yii\autclient\client\Github)
              {
                  $safe_attributes = [
                      'social_media' =&gt; 'github',
                      'id' =&gt; $attributes['id'],
                      'username' =&gt; $attributes['login'],
                      'name' =&gt; $attributes['name'],
                      'email' =&gt; $attributes['email'],
                  ];
              }
          return $safe_attributes;
      }
  
      public function actionIndex()
      {
          return $this-&gt;render('index');
      }
  
      public function actionLogin()
      {
          if (!\Yii::$app-&gt;user-&gt;isGuest) {
              return $this-&gt;goHome();
          }
  
          $model = new LoginForm();
          if ($model-&gt;load(Yii::$app-&gt;request-&gt;post()) &amp;&amp; $model-&gt;login()) {
              return $this-&gt;goBack();
          }
          return $this-&gt;render('login', [
              'model' =&gt; $model,
          ]);
      }
  
      public function actionLogout()
      {
          Yii::$app-&gt;user-&gt;logout();
  
          return $this-&gt;goHome();
      }
  
      public function actionContact()
      {
          $model = new ContactForm();
          if ($model-&gt;load(Yii::$app-&gt;request-&gt;post()) &amp;&amp; $model-&gt;contact(Yii::$app-&gt;params['adminEmail'])) {
              Yii::$app-&gt;session-&gt;setFlash('contactFormSubmitted');
  
              return $this-&gt;refresh();
          }
          return $this-&gt;render('contact', [
              'model' =&gt; $model,
          ]);
      }
  
      public function actionAbout()
      {
          return $this-&gt;render('about');
      }
  
  
      public function actionCommentary()
      {
          $model = new \app\models\Commentary();
          // return $this-&gt;render('commentary',['model' =&gt; $model,]);
  
          // Jika form di sumbit dengan method POST
          if (Yii::$app-&gt;request-&gt;post())
          {
              $model-&gt;load(Yii::$app-&gt;request-&gt;post());
              if($model-&gt;validate()){
                  Yii::$app-&gt;session-&gt;setFlash('success','Thank You');
              }
              else {
                  Yii::$app-&gt;session-&gt;setFlash('error','Sorry, something wrong');
              }
              return $this-&gt;render('result_commentary',['model'=&gt;$model,]);
          }
              else{
                  return $this-&gt;render('commentary',['model'=&gt;$model,]);
              }
      }
  
      public function actionQuery()
      {
          $db = Yii::$app-&gt;db;
          $command = $db-&gt;createCommand('SELECT * FROM employee');
          $employees = $command-&gt;queryAll();
          // Ekstrak data
          foreach ($employees as $employee)
          {
              echo "&lt;br&gt;";
              echo $employee['id']." ";
              echo $employee['name']." ";
              echo $employee['age']." ";
          }
      }
  
          public function actionQuery2()
          {
              $db= Yii::$app-&gt;db;
              // return a single row
              $employee = $db-&gt;createCommand('SELECT * FROM employee where id=1')
              -&gt;queryOne();
              echo $employee['id']." ";
              echo $employee['name']." ";
              echo "(".$employee['age'].")";
              echo "&lt;hr&gt;";
              // return a single column (the first column)
              $names = $db-&gt;createCommand('SELECT name FROM employee')-&gt;
              queryColumn();
              print_r($names);
              echo "&lt;hr&gt;";
              // Binding Parameter 
              $employee = $db-&gt;createCommand('SELECT * FROM employee WHERE id=:id'
                  ,['id'=&gt;2])-&gt;queryOne();
  
              // INSERT (table name, column values)
              //$db-&gt;createCommand()-&gt;insert('employee',['name'=&gt;'Nur','age'=&gt;'99',
              //    ])-&gt;execute();
  
              // UPDATE (table name, column values, condition)
              //$db-&gt;createCommand()-&gt;update('employee',['age'=&gt;'30'], 'id = 7')
              //-&gt;execute();
  
              // DELETE (table name, condition)
              //$db-&gt;createCommand()-&gt;delete('employee', 'id = 7')
              //-&gt;execute();
  
              // table name, column name, column values
              $db-&gt;createCommand()-&gt;batchInsert('employee',
                  ['name', 'age'],
                  [
                     ['Nur', 25],
                     ['Dani', 32],
                     ['Nurul', 40],
                  ])-&gt;execute();
          }
  
          public function actionActiveRecord()
          {
              $employees = \app\models\Employee::find()-&gt;all();
              foreach($employees as $employee)
              {
                  echo "&lt;br&gt;";
                  echo $employee-&gt;id." ";
                  echo $employee-&gt;name." ";
                  echo "(".$employee-&gt;age.") ";    
              }
          }
  
          public function actionSignup()
          {
              $model = new \app\models\SignupForm();
              // use session
              $session = Yii::$app-&gt;session;
              $attributes = $session['attributes'];
  
              if ($model-&gt;load(Yii::$app-&gt;request-&gt;post()))
              {
                  if ($user = $model-&gt;signup())
                  {
                      if ($session-&gt;has('attributes'))
                      {
                          // add data user_social_media
                          $user_social_media = new UserSocialMedia([
                              'social_media' =&gt; $attributes['social_media'],
                              'id' =&gt; (string)$attributes['id'],
                              'username' =&gt; $attributes['username'],
                              'user_id' =&gt; $user-&gt;id,
                              ]);
                          $user_social_media-&gt;save();
                      }
  
                      if (Yii::$app-&gt;getUser()-&gt;login($user))
                      {
                          return $this-&gt;goHome();
                      }
                  }
              }
  
              if ($session-&gt;has('attributes'))
              {
                  // set form field with data from social media
                  $model-&gt;username = $attributes['username'];
                  $model-&gt;email = $attributes['email'];
              }
  
              return $this-&gt;render('signup', ['model' =&gt; $model,
                  ]);
          }
  }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/tKYrC.png" alt=""></p>