Tag Archives: yii 2 tutorial

Yii 2 Dropdown List with Boolean Values

Sometimes it’s the simplest tasks that cause us the most grief. For example, a couple of days ago, I conceived of and wrote a tutorial for Super Simple RBAC in Yii 2 in about 20 minutes. What got me excited about that tutorial is that I reduced down the complexity of implementing RBAC, in other words granting special privileges and access to users with a role value of Admin, to six simple steps.

Of course that would not be possible if not for Yii 2. I know of no other framework that hands you so much power out-of-the-box that can help you move along so quickly. I’ve already gotten some great feedback on it and it seems like a nice solution for those who need admin users, but don’t want it to be too complex.

I cover this subject in my book, Yii 2 For Beginners in great detail, with a somewhat more robust solution with graphical UI for assigning roles. Also, a quick word of thanks to everyone who has purchased a copy, I appreciate your support.

Anyway, writing the RBAC tutorial had me feeling like a jr. Ninja and I was pretty happy about it. Unfortunately, I got splashed down to Earth on something really simple that took me a couple of hours to get right.

Have you ever had that frustrating feeling of knowing that what you want to do is so simple, and yet you just don’t know the right syntax to do it? So off you go, into experimentation mode to try to figure it out.

Now it would be nice if you could just look up everything in one awesome book, and the official guide is a great work in progress, but as of this writing, it is still incomplete. And even when it is complete, it is not going to cover every scenario.

It’s also not always clear what the best path to take is. For example, I’ve gotten quick at creating the little methods on the model that define relationships, and these are very useful for relationships. You can create dropdown lists with these methods in the views that really make your forms and view pages very intuitive for users.

But the ones I’m used to doing are based on relationships, which means they are built a certain way, involving other models and data tables. Now that sounds more complex, and it probably is, but like I said, I’ve done enough of them to be fairly comfortable with them at this point. I cover them extensively in my book.

But what if you just need to return a boolean value in a dropdown list that you want represented as a yes or a no? Does it make sense to put that in a DB table and create a relationship around it?

This is where the conversation gets interesting. You could do it that way, and if you were following a strict convention, doing it the same way as your other relationships, there’s some effeciency in that. You are always doing things the same way, therefore your code is easier to maintain and extend.

But here’s the catch. A boolean as a data structure is highly efficient, especially with MySql. That means if you get into complex querries that utilize the boolean value, it’s better to have the data type enforced as a boolean, MySql will perform better. It may only be a small difference, but small differences scaled over a large project can really add up.

Advertisements

Yii 2 Mobile First Design

One of the amazing things I love about Yii 2 is that it delivers a mobile-first, device scaling interface right out of the box. This is done via Twitter Bootstrap, which is the default implementation.

I never really knew how powerful this was until I worked on my template that I describe in my book, Yii 2 For Beginners.

I’ve never really had any talent for frontend design, and always felt that programmers were being punished for having too much fun coding by having to deal with frontend css, jquery, etc. Life would be too perfect if not for frontend development. I’m sure you can relate to that.

However, with the adoption of Twitter Bootstrap, that is starting to change. And maybe I should acknowledge just how awesome that frontend framework really is, since it does so much.

For example, you know those really cool top pins, where the top nav is pinned to the top of the page? That is out-of-the-box standard in Yii 2 courtesy of bootstrap. Another thing about it that is really cool is that when you size down the browser, it automatically detects the size of the browser and compensates. You don’t have to write a mobile version, it’s already there for you, how cool is that?

Plus Yii 2 has really cool bootstrap widgets designed to make it easy to integrate your view code with Bootstrap. I think you’ll be amazed at how much you get out-of-the-box.

I just did a quick tutorial on the dropdown nav and dropdown menu, so you can find that just by clicking the link. You’ll see how easy it is to implement.

In my book, I don’t focus too much on frontend, but we do look at some nice widgets, such as a pretty JUI DatePicker, Collapse, Alert, and more. It’s so simple when you see it in action.

Speaking of my book, please let me mention that I recently got my first book review from Vegibit:

“Another great resource is a great book by Bill Keck who maintains a blog about Yii. You can get the book at leanpub right here. It’s a great resource because it takes the perspective of someone who is new to the framework and is diving in with a self learning crash course in getting things working with Yii. This real world approach is valuable in learning the key concepts when the rubber hits the road so to speak.”

Thank you Vegibit for the kind words. When you get a chance, check them out, they are a good source for tutorials on Yii 2.

With the whole world moving toward mobile-first development, you can be confident that when you are developing on Yii 2, you are using a framework that gets it. The framework itself will provide most of what you need, right on install, and then after that, it’s easy to import extensions from Packagist.org.

I take a certain amount of pride in seeing the browser scale perfectly with my UI, even in reality, it wasn’t me, it was bootstrap. It’s just so cool!

If you would like more info on Bootstrap itself, just visit Get Bootstrap.

In a future tutorial, I’m going to write about how to configure your Yii 2 application to use a CDN for Bootstrap, jquery, and font-awesome, the dynamic trio of libraries that will make your UI sizzle. These libraries help take the drudgery out of frontend UI work and it makes development more fun, which is half the battle. Using a CDN will make them download faster and we all need that.

Feel free to add your comments to our blog and join the conversation. Thanks for your support!

Yii 2 RBAC Tutorial

Once again a warm welcome goes out to all the programmers and developers around the world who are discovering this blog. I get amazed every day when I see the stats and the diversity in the countries represented. It gives me the hope of a common language for the world and a framework like Yii 2 is a great place to express that.

Also, thanks to everyone who has taken part in the polls on this site. Over 1000 developers have voted on many topics relevant to today’s php community. Your comments are also appreciated, so please feel free to vote and comment.

And also, much gratitude for everyone who has purchased a copy of Yii 2 For Beginners, with your support I can continue my work, and I really appreciate it.

Ok, so the topic here is RBAC. This stands for Role Based Access Control and this can be difficult to implement in any framework. The Yii 2 advanced template comes with a working user model out of the box and this makes it fairly easy to get up and running. The thing is every site needs access control, especially if you are going to have a front end and back end to the site, and if you are going to have users with special privileges, such as admin users, who will have access to admin functions in the backend of the application.

The Yii 2 advanced template conveniently divides itself into frontend and backend out-of-the-box, so there again, it’s helping you. It stops short, however, of handing you a working RBAC model with the template. The reason for this is that many applications will have many different requirements and they need to leave the framework as open-ended as possible.

Yii 2 does have an authManager component with a complete RBAC implementation that is fully scalable and robust. You can read about RBAC in the docs. And if you want to use that, it’s perfectly fine. Personally, I found it to be a little rigid for my needs.

This is not saying anything bad about what they have, it’s just it’s impossible to anticipate every scenario, and its easier to build something to suit your own needs than follow someone else’s pattern. Plus there is a learning curve as there is with everything.

This is one of those instances where I really feel it’s better to write your own code, you will be closer to it, and it will be easier in the long run for you to work with it. Some may disagree with that statement, but like a lot of things in programming, it comes down to personal preference, so feel free to decide for yourself.

In my book, I layout an RBAC pattern that is easy for beginners to grasp and is something you can build on. But since it’s meant to be a little more robust for long-term use, it doesn’t lend itself to a quick tutorial.

At the same time, I noticed in the forum that there were a lot of people asking about how to implement RBAC. So I asked myself, is it quick and easy for someone to get up and running with RBAC if they just want user/admin roles? No. Wait… Yes it is!

I came up with a six step RBAC tutorial, which I’m linking to because I made a wiki tutorial out of it on the Yii Framework site.

You will need to have a fresh install of the Yii 2 advanced template. They have a complete set of setup instructions there. I cover it extensively in my book, with a bunch of jpgs to help you see what it is supposed to look like.

Anyway, for the tutorial, it’s a more basic version of what we cover in the book. I was able to bring it down to just six steps, it doesn’t require any outside plugin or extension, and you can do it in less than 20 minutes. I’m really happy about that.

It also uses Yii 2’s matchCallback method on behaviors, which I felt was good way to do it, since it leaves the main controller actions less cluttered. It’s really easy to implement.

Now RBAC is not the first subject you should jump into if you are just starting with Yii 2, and depending on your skill level, it can be difficult. The six step tutorial is about as simple as it gets, but you need to get the advanced template setup and working first, so make sure you have done that step before moving into RBAC.

On the other hand, I don’t know of any other php framework that can move you so far along, so quickly with RBAC. Yii 2 does 99.9% of the work, you have to love that.

Got my first book review from Vegibit:

“Another great resource is a great book by Bill Keck who maintains a blog about Yii. You can get the book at leanpub right here. It’s a great resource because it takes the perspective of someone who is new to the framework and is diving in with a self learning crash course in getting things working with Yii. This real world approach is valuable in learning the key concepts when the rubber hits the road so to speak.”

Feel free to add your comments below. We would love to hear from you. Thanks again for your support.

Yii 2 Dropdown Navigation

Yii 2 Dropdown Navigation and Menu tutorial

I would like to extend a warm welcome to all our friends from around the world who are just discovering this blog. Doing this blog, and seeing all the traffic from so many countries, it really does show me how much we all have in common, no matter where we are from. International bounderies are just an artificial construct, and not necessarily a good one. But as programmers and developers, we get to transcend all that and play in a very fun space.

Speaking of fun, over 1000 developers have taken part in the polls on this site, and I would encourage you to participate, either by voting or commenting or doing both, let your voice be heard.

You may have heard me say this before and most likely, you will hear me say it again:

Thanks to everyone who has bought Yii 2 For Beginners, I appreciate your support.

Now anyone who knows me knows that I try to avoid frontend development as much as possible. It’s like God invented frontend development just to irritate backend developers, who otherwise just enjoy coding a little too much. But with Yii 2’s native integration of Bootstrap 3, a mobile responsive css out of the box, there’s no reason to feel that way.

Yii 2 has a number widgets that make integrating with Bootstrap easy. The tricky part is finding the documentation on them. I was following the forum and saw a lot of questions on Dropdown Navigation or a dropdown menu, as in, how do we do it? That’s a really basic question, everyone will need this at one point or another.

Now trying to be helpful, I searched for the answer and came up with nothing. I even dug into the source code of the widgets to see if I could figure it out. Somewhere along the way, I figured it out. Of course I have no way to know if this is the “official way” to do it, but I’ve tested it and it works. So here is the implementation:

Yii 2 Dropdown Navigation:


echo Nav::widget([
                'options' => ['class' => 'navbar-nav navbar-right'],
                'items' => [
        
                            ['label' => 'Top Label', 'items' => [
                            ['label' => 'Action', 'url' => '#'],
                            ['label' => 'Another action', 'url' => '#'],
                            ['label' => 'Something else here', 'url' => '#'],
                        ]],
        
                    ],
    
            ]);

Turns out it’s just a nested array inside the items array. So simple! I know they are working on the documentation and that Yii 2 has just been released, so we all just have to have patience as they put all the docs together. They are doing a good job of it, the doucmentation they have is clear, we just need more of it.

Another request I see often in the forum is for a working RBAC solution. I’ve developed a nice solution in Yii 2 For Beginners, it’s easy to implement, with a full backend UI, but it’s one of the more extended lessons in the book and it’s too big for a blog post.

Getting back to the Yii 2 DropDown Navigation widget, please remember you have to echo the widget inside the view. That means you have to place it within Php tags. Also, if you want to the dropdown navigation inside the existing Navbar widget that comes with the default Yii 2 installation, you need to place it somewhere within the widget begin and widget end tags:


NavBar::begin([
                'brandLabel' => 'Yii 2 Build <i class="fa fa-plug"></i>',
                'brandUrl' => Yii::$app->homeUrl,
                'options' => [
                    'class' => 'navbar-inverse navbar-fixed-top',
                ],
            ]);

//your nav widget somewhere inbetween.

NavBar::end();


Another tip is you can see I included a call to font-awesome’s fa fa-plug in the brandLabel parameter of the NavBar widget. Font-awesome is a great library and most likely, you will want to include in your project. It’s also a topic, we cover in the book.

Just keep in mind that if you come up against a situation like not knowing how to do a dropdown menu in Yii 2, the answer is out there and someone will help you. The Yii 2 community is very active and willing to help. It’s a great framework and I’m committed to helping you make the most of it.

Yii 2 Mailer and Auto-Responder

Yii 2 Mailer Tutorial

This Yii 2 mailer tutorial implements a method to send response messages via email to users of the application. This is sometimes called an auto-responder.

This tutorial is not included in my book, Yii 2 For Beginners, but I thought it would make a great addition to the template that the book builds.

This is not a short tutorial, even though in reality, there isn’t much code. The reason is that we are not only going to talk about how we are approaching our methods, but also why. The why is very important.

A couple of years ago, I discovered a youtube video that talks about how important “why” is, and ever since then, I’ve made it part of my lesson plans.

Also, my blog is geared toward beginners, so I take great pains to explain in great detail what we are doing, what decisions we made, and why we made them. We want to not only advance your understanding of Yii 2, but we also want to learn a little about design principles and their application.

The goal, as always, is to make the final code as pretty, thin, and usable as possible. Ultimately, the email trigger method will be in a controller, so we always want to keep that code as clean as possible.

What do $foo and $bar actually mean in PHP?

Let’s start with a warm welcome to anyone from around the world who is just discovering this blog. Over 1000 developers have taken part in the polls on this site and I would encourage you to participate, let your voice be heard.

Also, thanks to everyone who has bought Yii 2 For Beginners, I appreciate your support. Starting this week, I will be adding tutorials on Yii 2 that build off of examples in the book, so I hope this can be a great resource for you.

Ok, so what is up with $foo and $bar? The use of $foo, and it’s companion $bar, in examples and lessons has always bothered me. One reason for that is that I know the origin of the composite word, Foobar, which is derived from fubar. Fubar is an epression that started in the US military. It stands for “fucked up beyond all recognition.”

So once upon a time, in the early days of programming, someone apparently thought it was clever to use a phonetic variation of fubar, split in half to use in programming examples. In other words, it was a joke. It was a joke, however, that caught on, and so now we seem to be stuck with it.

So what’s wrong with that? Ok, here’s the problem. Some people, like myself, know the origin of the word. The word itself has meaning. That meaning gets injected into the example on a subliminal level, which distracts from understanding the objective of the lesson.

Also, since $foo and $bar combine to represent a single word, the first thing I always try to see is if they are meant to be related that way when they are used in an example and more often than not, they are not meant to be related, though in some cases, one is used as a child of the other. You can see how confusing this can get.

It’s not that I don’t have the brain power to overcome the inference of fubar, but on the other hand, I would rather not waste bytes or neurons, precious as they are, on something like that. I have a much better use for them elsewhere.

Now you could say I’m in the minority, and that most people, especially those around the world who don’t speak english as a first language, are not going to have that distraction and you would be right about that. However, $foo and $bar still make for bad examples. Here’s why:

Even without the inference, using $foo and $bar is like using $could_be_anything_1 and $could_be_anything_2 or as the way my brain sees it, $lazy_example_1 and $lazy_example_2.

Wouldn’t be better for example, if you were going to explain arrays to people, to do it in a way that also points them in the right direction for future use and future lessons. For example, here we have a snippet from PHP.net on the new array syntax:

// as of PHP 5.4

$array = [
"foo" => "bar",
"bar" => "foo",
];

And look, they used my favorite word for the example, I didn’t have to go far to find someone using it. So just to reiterate why this is so bad, the first key is foo and has a value of bar, the second key is bar and has a value of foo. Does this mean they are interchangeable in the code and that they are equal to each other? Of course not. Arrays don’t work that way. But imagine you were just learning. You could see how that would potentially be confusing.

Robert Martin, Author of Clean Code, uses an interesting phrase, “lies and disinformation.” He is referring to comments in code that grow outdated in time because they are not maintained as the code changes. A bad choice of language in tutorials and examples is just as harmful. It slows down the learning process and makes it less fun.

Imagine the poor guy just learning PHP and programming having to spend an extra ten minutes of his time to realize that foo and bar are not equal to each other. If that happened to me, I would be angry and want my time back. Nothing is as precious as time and anything that degrades it in a learning enviroment is as bad as “lies and disinformation.”

Imagine an array example instead:

// as of PHP 5.4 example array named basket, where “string” is key and integer is value:

$basket = [
"apple" => 1,
"cookie" => 4,
];

Now obviously, there is a little more color to the example. Also I added more to the comment for clarity, even though those aspects might be explained elsewhere. It doesn’t hurt to have it there, because when people do a Google search, they may come directly to this snippet, you never know.

Why choose the word $basket? Well, what would a future or current programmer possibly work on that would require an array? That list is probably endless, but one good example would be a shopping cart. And right away, as a human, I’m a lot more interested in the example. Arrays might be fun if I can play with apples and cookies. I might even start to get creative about what I can do with the basket.

So obviously this is as basic as it gets, but it does have implications. We have seen a movement in modern PHP towards more clear snytax, and what I mean by that is code that makes its intentions more clear.

The modern PHP frameworks like Laravel and Yii 2 have done a good job making the code more intuitive. In fact I think Taylor Otwell, Laravel inventor and developer, has been very influential in this regard. I initially found his framework very attractive, but then Yii 2 came out and as you can tell from the history of this blog, and the book I wrote about it, I fell in love with it.

An example of excellent and intuitive syntax in Yii 2 is the behaviors method that you can use on either a model or a controller. We’re about to take a quantum leap in complexity from the array example, but as long as we give a good example, we will understand it.

A typical implementation of behaviors in a model would look like this:

public function behaviors()
{
  return [
     'timestamp' => [
          'class' => 'yii\behaviors\TimestampBehavior',
          'attributes' => [
              ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
              ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
          'value' => new Expression('NOW()'),
            ],
        ];
     }

Screenshot of the code with no scroll:

yii 2 behaviors

If you are following along from the book, this example appears in the User model and Profile model. We use a different type of behavior for controllers, but you can get a clear idea of how cool and how flexible this concept is.

TimestampBehavior is one of Yii 2’s out-of-the-box behaviors, so everything is in place that you need to attach it to any model. All it’s doing here is automatically setting the value of two attributes, ‘created_at’ and ‘updated_at’ with a ‘value’ of ‘NOW()’ before insert or update.

This means before any record is created or updated, the timestamp value is set, and, assuming that you have the corresponding columns on your DB table in DATETIME format, you will get the desired result and the fields in your table will be updated with the current DATETIME.

Can you see how intuitive the concept is and how clear the code is? Anyway, let’s just step through this to make sure we understand it.

By configuring the behavior, we influence how the model will work. We give the behavior a name, in this case ‘timestamp.’ We tell it what class to use, in this case ‘yii\behaviors\TimestampBehavior.’

Next we tell it which attributes we want to affect, and we use ActiveRecord::EVENT_BEFORE_INSERT to tell it when and how to use it. In other words, it will set the value of the attribute before inserting or updating, which is made fairly clear from the name of the event.

And then finally, what ‘value’ we want to give it. We’re using an instance of the expression class, which let’s us define what type of value we want, which allows us to pop in the MYSQL syntax ‘NOW()’, so ActiveRecord can hand it into the insert statement.

You know the syntax is well-written when it is easier to understand than the verbal explanation. At least it seems that way to me. I’ve been staring at it for a while now. It just seems clearer and clearer to me, which is always a good sign.

Now imagine the above example as:

 public function behaviors()
    {
        return [
            'foo' => [
                'class' => 'foobar',
                'attributes' => [
                    qux => ['baz1', 'baz2'],
                    qux => ['baz2'],
                ],
                'value' => new Expression('quux'),
            ],
        ];
     }

Screenshot of the code with no scroll:

bad behaviors

That’s not realistic, no one would do that to you, at least I hope they wouldn’t. Anyway, I think you get the point. A real example makes you want to play with the system. A $foo/$bar example is just fubar. Feel free to take the poll and let us know what you think.

Yii 2 extensions

I was lucky enough when I started playing with Yii 2, about 6 months ago, during the alpha release, to get some help answering the most basic questions about creating relationships and tying models together. That help came in the form of Kartik Visweswaran, a Yii 2 innovator and enthusiast locaed in Bangalore India. Not only did Kartik help out in the forum, taking the time to support users, he also provided tutorials on the wiki, including this tutorial for a sortable, eager-loading search result in GridView.

And Kartik also built incredible extensions for Yii 2, so many in fact, he has them listed on his own site at Krajee.com.

I knew I was going to love his work when I implemented the tutorial I mentioned above, scenario 2, which was right on the money and took less than 15 minutes. I also integrated Kartik’s social extension, yii2-Social, which got me into Facebook widgets, again with minimal time spent. Part of the reason it goes so smoothly with integrating his work is that he documents it so well.

Last time I counted, he had 28 extensions/goodies on his site, with an incredible selection extending Gridview, navigation, form builders, file management, helpers, quality Bootstrap stuff to make your app pretty, and much more. If you have not checked it out yet, you are really missing out.

How lucky are we to have a great framework to play with, but great contributors too. This is what makes programming a lot of fun.

You can find a lot of cool extensions also at https://packagist.org/. Just type in Yii 2 and you will see the list of available items, 350 of them at this writing.

Now with Composer fully utilized by Yii 2, installing an extension is very simple. Just add it to your composer.json and do composer update and one minute later, it’s installed. Depending on the extension, you might have do some config, but that seems to clearer and easier these days with Yii 2. Kartik documents his extensions extremely well, so you will be up and running quickly.

If I understand Kartik’s blog correctly, he works full time programming and does his Yii 2 extensions in his spare time. You know you love something when it is your work and your hobby too. It helps explain why he is so prolific and so good at what he does. Also check out his WebTips blog, there is a great tutorial on the Yii 2 FileInput widget.

A lot of programmers are humble by nature and they don’t get the credit they deserve. This certainly applies to the core Yii 2 team, and also to the supporting developers like Kartik. These guys do an amazing job. I’m not shy about pointing that out. A lot of hard work goes into creating this stuff, and as a beneficiary of that work, I really appreciate it.

Another way to say thanks to developers like Kartik is to click and visit the sponsors on his site, and of course there is the donate button. A little contribution makes a big difference to the quality and quantity of open source options. If you find yourself using contributions often, please give something back. These guys will really appreciate it and you will see more great innovation that will help your development needs.

One of my goals with this blog is point people in the right direction when it comes to Yii 2, at least as best I can. So I’m definitly pointing in the direction of Kartik for Yii 2 extensions.

In the future, I’d like to profile more developers, especially if they are doing interesting things with Yii 2. Now that Yii 2 is in General Release, we will probalby see even more contributions. It’s a very exciting time for people who love the Yii 2 framework. Feel free to comment and take the poll, and please contact me if you wish to contribute to this blog.