Answer the question
In order to leave comments, you need to log in
How to split models in Yii2?
I came across the idea that when saving data from forms, it is worth validating the data first with a validating model, and then saving everything through a model inherited from ActiveRecord.
I understand the logic of this approach when you need to add data to the database. Then the code is quite simple
QuestionForm:
namespace backend\models;
use yii\base\Model;
class QuestionForm extends Model {
public $active;
public $question;
public $answer;
public function rules()
{
return[
['question','required'],
['answer','required'],
['active','boolean'],
];
}
public function create()
{
if(!$this->validate()) {
return null;
}
$model = new Question();
......
return $model->save() ? true : false;
}
}
public function actionCreate() {
$model = new QuestionForm();
if( \Yii::$app->request->isPost) {
if( $model->load(\Yii::$app->request->post()) && $model->create( ) ) {
...........
}
}
return $this->render('create', ['model' => $model]);
}
public function actionUpdate($id) {
$model = $this->findModel($id);
if( \Yii::$app->request->isPost) {
if($model->load( \Yii::$app->request->post()) && $model->save() ) {
$this->setSuccessAlert();
$this->redirect(['update', 'id' => $model->id ]);
}
}
return $this->render('update', [
'model' => $model,
]);
}
Answer the question
In order to leave comments, you need to log in
If you have a view model with validation rules (and your QuestionForm is essentially a view model) and you want to completely get rid of validations in ActiveRecord then you should use it in actionUpdate, not ActiveRecord. Those. load the data from the post into the QuestionForm, validate it, and after that drive it into AR and save it...
For example, in its simplest form it could look like this:
class QuestionForm extends \yii\base\Model {
public function findModel($id){
$model = MyActiveRecord::findOne($id)
return $model;
}
public function update($id)
{
$model = $this->findModel($id);
if (is_null($model)) {
return false;
}
$model->load($this->attributes, '');
return $model->save();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question