I have hard time getting my form to insert data into the database. I followed the guide from here:Active Record. When click the create button, the form seem to work but when I check my database there’s no entry.
Here’s my code:
MODEL
namespace it\alumregistry\models;
use yii\base\Model;
use yii\db\Query;
use yii\db\ActiveRecord;
use Yii;
use yii\helpers\ArrayHelper;
use yii\data\SqlDataProvider;
use yii\data\ArrayDataProvider;
use yii\db\ActiveQuery;
use yii\validators\EmailValidator;
use yii\web\app;
class MSE_Gapps_Pending extends ActiveRecord
{
public $jenzId;
public $email;
public function rules()
{
return [
[['email', 'jenzId'], 'safe'],
['email', 'validateAtLeastOne', 'skipOnEmpty' => false],
];
}
public function attributeLabels()
{
return [
'jenzId' => 'Your ID',
];
}
public function validateAtLeastOne($attribute, $params)
{
if (empty($this->email) || empty($this->jenzId)) {
$this->addError('email', 'All search terms need to be provided.');
$this->addError('jenzId');
}
}
public static function MSE_Gapps_Pending() {
return 'MSE_GAPPS_PENDING';
}
Here’s the Controller
public function actionCreate()
{
$model = new MSE_Gapps_Pending();
$modelCanSave = false;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->ID_NUM = '775577';
$model->Alt_Email ='emailtest@gmail.com';
$model->insert();
}
Would someone please point what am I doing wrong here?
No, I didn’t not use Gii. The ‘email’ and ‘jenzId’ do not represent columns in the table but wanted to get the record from the form so that I can insert them into the table.
You have to create your MSE_Gapps_Pending model extending "Model" instead of "ActiveRecord" when you want it to be independent of any db table.
But a model extended from “Model” doesn’t have any method to read from or write to db table. You need to do it using another model extended from “ActiveRecord” or using DAO.
Something like this:
public function actionCreate()
{
$model = new MSE_Gapps_Pending();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model2 = new SomeModel(); // SomeModel is an ActiveRecord model
$model2->ID_NUM = $model->jenzId;
$model2->Alt_Email = $model->email;
$model2->save();
return $this->redirect(['index']);
} else {
return $this->render('login', [
'model' => $model,
]);
}
}