Yii Framework 2.0: update and insert data into database from form

Hi guys! Today I want to speak about how you can update and insert data into database from a form in Yii Framework 2.0. I will explain to you how you can insert data from your standart Yii's Contact form into your database.

So, first of all, you must create a new table in your database. The table must be called form. In the table you must create 5 fields: id, name, email, subject, body.

Next, open your models/ContactForm.php file and you must modify the contact function from

public function contact($email)
{
if ($this->validate()) {
Yii::$app->mailer->compose()
->setTo($email)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();

return true;
} else {
return false;
}

to

public function contact($email)
{
if ($this->validate()) {
$form = new Form();
$form->name = $this->name;
$form->email = $this->email;
$form->subject = $this->subject;
$form->body = $this->body;
$form->save();

return true;
} else {
return false;
}
}

Now, this function will insert the data from the form in your database! In the same way you can update the data from your database.

Video tutorial:









Leave a Comment