Hello I am new to Yii framework and I am trying to save data to database. It won't work I don't know where is the problem.
Controller:
namespace app\controllers;
use app\models\Client;
use Yii;
use yii\web\Controller;
class ClientController extends Controller {
/**
* Displays Client_Register.
*
* @return string
*/
public function actionAdd() {
$model = new Client();
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
return $this->refresh();
}
}
return $this->render('add', ['model' => $model,]);
}
}
View:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'name')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'lastname') ?>
<?= $form->field($model, 'birthday') ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-primary', 'name' => 'add-button']) ?>
</div>
<?php ActiveForm::end(); ?>
Model:
namespace app\models;
use yii\base\Model;
/**
* Client is the model behind the client form.
*/
class Client extends Model {
public $id;
public $name;
public $lastname;
public $birthday;
public static function tableName() {
return 'clients';
}
/**
* @return array the validation rules.
*/
public function rules() {
return [
[['name', 'lastname', 'birthday',], 'required'],
];
}
public function attributeLabels() {
return [
'id' => 'Id',
'name' => 'Name',
'lastname' => 'Last Name',
];
}
}
I have already created the database with migrations. But I don't why does this error happen. Should I include some save method in model or how can I solve this issue. I looked at other examples too. They are identical as my code. Do you have any idea where is the problem?
Your Client
class extends Model
, which does not support saving data in database, thus save()
method is not defined. If you want to work with database record, your model should extend ActiveRecord
:
class Client extends ActiveRecord {
public static function tableName() {
return 'clients';
}
public function rules() {
return [
[['name', 'lastname', 'birthday'], 'required'],
];
}
public function attributeLabels() {
return [
'id' => 'Id',
'name' => 'Name',
'lastname' => 'Last Name',
];
}
}