Yii 2 Test Controller

Again I’m going to use my test controller to see how it works.

public function actionIndex()
          $date = "Sep 5, 2014";
         $new_date_format = date('Y-m-d', strtotime($date));
            $date = $new_date_format;
         return $this->render('index', [
            'date' => $date

So this is just simple conversion of one format to another, using two built in php functions, date and strtotime. It now returns the correct date in the view:

/* @var $this yii\web\View */

    <?= $date ?>

If you play around with it, you can see that entering gibberish returns the wrong date, but this is not as harsh as the exception that was being thrown, so I could live with it for now, until I come back and do more validation or until the datepicker widget is fixed.

This was not a random example, the DatePikcer returns a format like Sept 5, 2014, and MySql DateTime needs it as Y-m-d (which is 2014-09-05). So this patch comes in very handy as a temporary fix.

Perhaps this solution could be written more concisely. It can be done with one less line of code for sure. Play around with your new test controller to figure out how to write it better and don’t look at the code below.

Were you able to get it? If not, here is the solution:

public function actionIndex()
          $date = "sep 6, 2014";
         $date = date('Y-m-d', strtotime($date));
         return $this->render('index', [
            'date' => $date

I hope you’ve enjoyed this tutorial on test controllers for Yii 2. A test controller can be a useful tool in developing your application, so I hope you can apply these methods to your development needs.

Thank you to everyone from around the world who reads this blog, your support is appreciated. Links, reviews, and comments will be greatly appreciated, thanks again and hope to see you soon!

One thought on “Yii 2 Test Controller”

  1. Thank you so much for this.
    I have been attempting to learn Yii 2.0 for about 2 weeks now and stumbling and fumbling my way through.
    A few minutes into this tutorial and it clicked in.
    You’ve done a great job of easily explaining how it all works, so thank you for taking the time to put this down for everyone to learn from.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s