This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Join our FREE webinar: Discover how Immunify360's advanced malware scanning secures your site. REGISTER NOW→

How to Create a Simple, Functional Contact Form Using Yii 2

Updated on July 15, 2021

5 Min Read

In the previous installment of this series, I developed a Hello World app using Yii2. In this tutorial, I will create a database with a table which will save the contact form data, and connect the database to the Yii2 application.

Creating Contact Form in Yii2

Let’s first create a database and a table.

Related: How To Host Yii 2 Framework On Cloudways Using Composer

Creating the Database

Open PHPMyadmin and create a database. Name it yii2 to make it easy to identify and associate with the project. Now create a table with the following schema:

CREATE TABLE `contact` (

 `id` int(11) NOT NULL,

 `name` varchar(50) NOT NULL,

 `email` varchar(50) NOT NULL,

 `message` varchar(255) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Nothing as Easy as Deploying PHP Apps on Cloud

With Cloudways, you can have your PHP apps up and running on managed cloud servers in just a few minutes.

Connecting the App to the Database

Now that we have successfully created the tables in the database, let’s connect the Yii2 app to the newly created database. Head to the config folder in the Yii2 basic directory and open db.php.

db.php

Change the dbname from yii2basic to yii2, enter the username and password and save the file.

Change dbname

Since the connection to the database is now established, let’s now create a model that will perform various operations on the table.

Related: How To Use Elasticsearch With Yii 2

Creating the Model

Since I am creating a model for the Contact table, the name of the model class will be same as the table’s name. I will extend from \yii\db\ActiveRecord a helper class of Yii2, that will help in accessing and manipulating data in the database.

Go to the models folder, create a new file and name it Contact.php (make sure that the first letter is capital). Now paste the following code in it.

<?php

namespace app\models;

use Yii;

use yii\base\Model;

class Contact extends \yii\db\ActiveRecord{

       /**

    * @inheritdoc

    */

   public static function tableName()

   {

       return 'contact';

   }

   /**

    * @inheritdoc

    */

   public function rules()

   {

       return [

           [['name','email','message'], 'required'],

           ['email', 'email'],

           [['name'],'string', 'max' => 50],

           [['email'], 'string', 'max' => 50],

           [['message'], 'string', 'max' => 255],

          

       ];

   }

}

Inside this class, I first created a function called tablename that returns the name of the table. Next, I created a function which defines the set of rules in an array:

public function rules()

   {

       return [

           [['name','email','message'], 'required'], //Checking that all the fields are required

           ['email', 'email'], // Validating that email is a valid email

           [['name'],'string', 'max' => 50], //Verifying that name is not greater than its max length

           [['email'], 'string', 'max' => 50], //Verifying that email is not greater than its max length

           [['message'], 'string', 'max' => 255],//Verifying that message is not greater than its max length

          

       ];

   }

One thing you might have noticed is that I haven’t created any function to insert data into the table.  Since we have extended our model with ActiveRecord, we don’t need to write input functions. Now let’s create an action which will handle this model and the form.

Creating the Controller

Go to the controllers folder and open SiteController.php. First, add the model to the top

use app\models\Contact;

Now create a new function in class and name it actionForms. Pastes the following code in it:

public function actionForms()

   {

       $model = new Contact();

       if ($model->load(Yii::$app->request->post()) && $model->save()) {

           Yii::$app->session->setFlash('contactFormSubmitted');

           return $this->render('forms', [

               'model' => $model,

           ]);

       } else {

           return $this->render('forms', [

               'model' => $model,

           ]);

       }

   }

Inside the function, first I created an instance of our Model:

$model = new Contact();

and then I check whether the request is a post and then save the data in the table by using $model->save(),  a built-in function in ActiveRecord that is used for inserting data into a table.

if ($model->load(Yii::$app->request->post()) && $model->save())

Next, we check whether the form is submitted. And then I rendered the form’s view along with the model data.

Yii::$app->session->setFlash('contactFormSubmitted');

           return $this->render('forms', [

               'model' => $model,

           ]);

If the request is not a post, The form’s view is rendered along with  $model along with it.

return $this->render('forms', [

     'model' => $model,

]);

I am sending $model along with the render function because it will have the data when a user submits the form. If the data does not validated, then it will be sent back to the user to correct it. The $model will help the user view the submitted data along with the errors.

Now let’s create our form view.

Creating the View

Go to the views folder>>site folder, create a new view and name it forms.php. Paste the following code.

<?php

use yii\helpers\Html;

use yii\bootstrap\ActiveForm;

$this->title = 'Contact Form';

?>

<h1><?= Html::encode($this->title) ?></h1>

<?php if (Yii::$app->session->hasFlash('contactFormSubmitted')): ?>

<div class="row">

   <div class="col-lg-5">

       <div class="panel panel-default">

           <div class="panel-heading">Message Sent</div>

           <div class="panel-body">

               <p><b>Name:</b> <?=$model->name?> </p>

               <p><b>Email:</b> <?=$model->email?> </p>

               <p><b>Message:</b> <?=$model->message?> </p>

           </div>

       </div>

       <div class="alert alert-success">

           Thank you for contacting us. We will respond to you as soon as possible.

       </div>

   </div>

</div>

   <?php else: ?>

<div class="row">

           <div class="col-lg-5">

               <?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>

                   <?= $form->field($model, 'name') ?>

                   <?= $form->field($model, 'email') ?>

                   <?= $form->field($model, 'message')->textArea(['rows' => 6]) ?>

                  <div class="form-group">

                       <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>

                   </div>

               <?php ActiveForm::end(); ?>

           </div>

       </div>

<?php endif; ?>

First,  there is the helpers class of Yii2, that we will be using in our views.

use yii\helpers\Html;

use yii\bootstrap\ActiveForm;

$this->title = 'Contact Form';

In the first part, the form checks whether the form is submitted or not. If the form is submitted, I than view the data provided along with confirmation.

<?php if (Yii::$app->session->hasFlash('contactFormSubmitted')): ?>

<div class="row">

   <div class="col-lg-5">

       <div class="panel panel-default">

           <div class="panel-heading">Message Sent</div>

           <div class="panel-body">

               <p><b>Name:</b> <?=$model->name?> </p>

               <p><b>Email:</b> <?=$model->email?> </p>

               <p><b>Message:</b> <?=$model->message?> </p>

           </div>

       </div>

       <div class="alert alert-success">

           Thank you for contacting us.

       </div>

   </div>

</div>

In the else part, I have created a form which the user will use to send the message. The form has been created using the ActiveForm helper of Yii2.

<?php else: ?>

<div class="row">

           <div class="col-lg-5">

               <?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>

                   <?= $form->field($model, 'name') ?>

                   <?= $form->field($model, 'email') ?>

                   <?= $form->field($model, 'message')->textArea(['rows' => 6]) ?>

                  <div class="form-group">

                       <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>

                   </div>

               <?php ActiveForm::end(); ?>

           </div>

       </div>

<?php endif; ?>

Now let’s test the code by going to action ?r=site/form.  The contact form will be shown.

Contact Form

Try sending a message using the form.

Contact Form in Yii2

Once the message is sent, the form is successfully designed and configured.

Contact Form Message

Now check the database. You will see that a new record has been added to it.

New Record in Database

You Might Also Like: How to Create a Contact Form in HTML and PHP

Conclusion

In this tutorial, we have created a form and saved its data in a database. In the next part of this series, I will demonstrate the versatility of Yiii2 through a to-do list using gii. Here is the complete list of topics covered in this series on Yii2.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahzeb Ahmed

Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now