Last updated on February 10, 2018
we sometimes need to modify user submitted data or based on user submitted data we need to do some calculation to fetch the values then, we will save that data in the database, so in order to achieve this, we will use modal events in YII.
For example, you might want to do API requests to fetch some values before a model instance is saved. To do so, just create a beforeSave() method within the model:
public function beforeSave() { if(parent::beforeSave()){ if ($this->isNewRecord) { $youtubeVideoObject = $this->youtubeGetData($_POST['MovieSrc']['youtube_url']); $this->creatd_on = date("Y-m-d H:i:s", time()); $this->modified_on = $this->creatd_on; $this->author_id = Yum::app()->user->id; $this->movie_duration = $youtubeVideoObject['duration']; . . . etc } else { $this->modified_on = date("Y-m-d H:i:s", time()); } } }
you can modify the data the way you want before saving it using beforeSave event.Based on isNewRecord property check, we can have different logic for the update and new records insert.
That’s it.