Problem Statement
I am currently working on a Yii2 project where I have a class that represents a table and this class contains a variable which is not directly related to any table column. Let's call this class CustomModel. Within CustomModel, I have a variable, let's say $customVariable, that I need to perform CRUD (Create, Read, Update, Delete) operations on.
Class Structure
php
class CustomModel extends \yii\db\ActiveRecord
{
public $customVariable;
// Other class properties and methods
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['customVariable'], 'safe],
];
}
}
What I've tried inside CustomModelController
public function actionCrud()
{
$model = new CustomModel();
if ($model->load(Yii::$app->request->post())) {
$model->save();
return $this->redirect(['custom-model/index']);
}
return $this->render('_form', [
'model' => $model,
]);
}
Inside the view form
<?php $form = ActiveForm::begin([
'fieldConfig' => [
'template' => '{label}{input}{error}',
'errorOptions' => ['class' => 'error'],
'options' => [
'class' => 'form-group form-group-default'
],
],
]); ?>
<div class="row ">
<div class="col-md-6 col-xl-3">
<?php echo $form->field($model, 'customVariable')->textInput(['maxlength' => true]) ?>
</div>
</div>
<div class="form-group pull-right">
<?php echo Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
Active Record is always mapped to the table column, model itself being representative of a single row. Trying to updating a random variable not related to the database table is misuse of the AR pattern.
I suggest you use DAO to update random table fields.