I’m trying to create a widget to create a new model. It works okay so far, but I’m not sure if it is the right approach. I am not sure if the creation of the new model should happen in init() or run() or somewhere else (e.g. the Model itself).
Here’s what I have.
namespace frontend\components;
use Yii;
use yii\base\Widget;
use yii\helpers\Html;
use app\models\MessageBump;
class MessageBump extends Widget
{
public function init()
{
parent::init();
$model = new MessageBump();
if (Yii::$app->request->isPost) {
$model->item_id = Yii::$app->getRequest()->getQueryParam('id');
if ($model->save()) {
Yii::$app->session->setFlash('success', 'Bumped the user with a message!');
}
}
}
public function run()
{
$model = new MessageBump();
return $this->render('_MessageBump', [
'model' => $model,
]);
}
}
Is there a better alternative to do this?