Tag Archives: yii 2 framework

Yii 2 for Beginners Bonus Material Released

I’m happy to announce that the first chapter of bonus material for Yii 2 For Beginners has been released. The book has gone from a previous page count of 290 pages to 412 pages, so this is a very substantial addition.

Everyone who purchases Yii 2 For Beginners gets FREE updates for the life of the book. Just log into your leanpub account and download the latest version. I’m planning to continue to do updates and write bonus material for the foreseeable future. There are a number of reasons for this.

1. Striving For Excellence. I want to build a reputation for excellence and quality as a technical writer and I’m deeply committed to this project.

2. Framework Updates. I want to stay on top of Framework updates. The latest version of Yii 2 is 2.0.2, released two days before I released my bonus material. This meant I had to frantically rebuild the entire application from scratch, following the directions in the book, just to make sure everything is working. There were a few minor changes and I caught them all.

3. Maintaining the Template. The template we build in the book is a useful template for creating sites, including my own. I need to stay on top of version changes as much as anyone else, and as I’m doing that, it only makes sense to share the version improvements with my readers.

4. Sharing the Journey. Working with Yii 2 is an amazing experience that I would like to share with my fellow programmers and engineers. Working on this book is a way to express my passion for Yii 2 and grow at the same time.

I’d like to thank everyone who emailed or commented for the wonderful feedback, especially the positive reviews on GoodReads.

I really appreciated the notices on the typos as well. Most of the typos are trivial, but I still want to correct them. I won’t be satisfied until the book is 100% free of typos and I think we are probably close to that now.

I know for a fact the code is 100% working. The build I did over the past few days was from code taken directly from the book, via the gists, and it works perfectly. For anyone who doesn’t know, a gist is a code snippet hosted by Github.

Copying code from a PDF can be a real pain and I had multiple requests from readers to post the code. So, in response, I have supplied a gist for any block of code that is over 3 lines. The gists are inline in context in the book, so you just click a link and you get the relevant code. This means you don’t have to bookmark or organize anything, it’s already done for you.

New in this Update

1. Yii 2 Version Update. I already mentioned that Yii 2.0.2 was released a couple of days before I finished and this was perfect timing for me. The three notable changes concerning the template were:

A. The advanced template doesn’t ship with a role column on the user table like it did before.

B. Forgot password methods changed.

C. The typo generated by Gii when creating a controller has been fixed.

So nothing here required any dramatic changes on my part, just some instructional text had to change. This worked out well. I should point out that I ran into an unknown problem when I tried to run composer update, composer just got hung up. Another user experienced an issue as well.  My work around was to build from scratch. I had to do this anyway because I had to test everything 100% on a new build. My code is 100% compatible with both Yii 2.0.1 and Yii 2.0.2. If you do a fresh build, everything will work perfectly.  So that’s the good news there.

2. Fine Tuning Core Book. Doing an update always gives me the chance to go back over the instructions in the book to fine tune them for maximum clarity. I also catch typos, and obviously any bugs in the code. I can’t claim a 100% on typos, but I know the code is 100% working because I use it myself, and like I said before, I just rebuilt the application from scratch using the code from the book. Nothing in the core book changed in terms of how we were doing things, so nothing of substance to report.

For those that don’t know, the core book takes you through setup and install of Yii 2, then onto building a reusable template that also includes:

  • A Working user model
  • User registration and login
  • User Profile
  • Forgot password recovery
  • Frontend and backend separation with Admin UI
  • Helper classes
  • Access control
  • Free/Paid content control
  • RBAC with backend UI
  • JUI DatePicker
  • Bootstrap Mobile Responsive CSS
  • Facebook Social Widgets
  • Font-Awesome Implementation

The bonus material extends the core template with useful features, at the same time, we continue learning more about the framework.

3. Autoresponder. In the bonus material, we build an auto-responder. This is similar to the one I talk about on the blog, only this is the full set of instructions, with tested code. So again you know it’s 100% working.

4. Dropdown Navigation. We implement dropdown navigation links from my own solution. It’s quick and easy and you will love it.

5. We build an FAQ model for the template. FAQs are common to most sites and this will come in handy. This implementation has a full frontend/backend UI with extensible data structure. It is very useful code.

6. Components. We build the component application structure and show you how to create a component in the Advanced Template, including all the config details.

7. Custom Widget. Creating widgets are easy once you know how. This is a very powerful piece of the Yii 2 architecture that you will fall in love with. I will be blogging more about this in the future, it’s just amazing.

8. Closing A Potential Hole. There is no hole in the code if everything is coded correctly, but what happens when someone makes a typo? This section makes a nice adjustment to the ValueHelpers class that helps prevent accidental exposure.

9. CDN. We finish the first round of bonus material with a simple config implementation to use CDN for the core CSS and JS assets. This can dramatically increase the speed of the application.

All in all, it’s over 100 pages of new material. To reiterate, this is all 100% FREE to anyone who has previously purchased the book. Just log into your leanpub.com account to download the latest version.

I really had to work hard to get this to you in a timely manner. I put another book-writing project on hold, so I could make sure I live up to the commitments in supporting Yii 2 For Beginners. Now I need a few days off before I collapse from exhaustion.

Thanks again to all the readers from all over the world who were supportive with positive comments and are supporting my work. Your feedback motivates me to keep going. For example, on GoodReads, we are averaging 4 out 5 stars, with some nice comments even from the lower rating, which came before the additional 100+ pages of material was added to the book.

Please keep the comments, links, positive reviews, and word-of-mouth-referrals coming, they are greatly appreciated. See you soon.

Yii 2 Gii code generation

One of things about Yii 2 that is drastically different from some of the other frameworks is Gii, it’s code generation tool. I cover the use of Gii extensively in my book, Yii 2 For Beginners.

On the surface, this might just seem like a fun feature to use, a time-saver in certain circumstances. And that’s probably true of a lot of code generators, they only take you so far. But Gii is different.

Gii is so powerful that it has very meaningful impact on work flow. And this impact reaches deep into our profession. You can look at it from two perspectives, one, the individual developer doing work for clients, and two, from a team perspective, which can bring you up to full enterprise level.

So let me talk first about how it impacts the individual, and since a lot of my readers are beginners, it will help them understand the importance of Yii 2 and Gii.

1. Planning. Use of Gii impacts planning. Before you code a single line of code, you can factor in not only the efficiency of Gii, but also the workflow.

For example, to start, you look at the scope of the project and begin sketching out the table structure. The more well-thought out this data-structure is, the useful Gii becomes. If you use foreign keys to relate tables, Gii will understand this and generate relationships in the models.

This gives you the ability to imagine the project, and better yet, diagram the tables in MySql workbench, before any PHP is involved. And once you know the number of tables you are working with, you will have some idea of how long basic development will take. This is possible because you can average how long each table takes to convert to model to controller to view.

In a typical implemenation, there are 8 files generated. And they also typcially need customization, but once you have an idea of what you generally use for that, even the 1st level of customization goes quickly. When I say quickly, I mean crazy fast. It’s awesome. Awesome is not a technical word, but you have to give me a pass on that one, I really love Gii.

2. Strong MVC Pattern. The code that Gii generates is a beautiful implementation of the MVC pattern. It’s probably the easiest structure to follow of all the frameworks because you literally get folders named models, controllers, and views. And once you understand how it’s all stiched together, it just makes perfect sense.

3. Learn Good Practices. As your workflow and project planning are impacted by Gii, you begin to develop a discipline to the structure. While you are certainly not locked into anything, if you follow the breadcrumbs of good practices that Yii 2 and Gii are putting out there for you, your project becomes very tight and focused. Things are always done the same way, at least at the base level.

It’s understood of course that I’m talking about the bones of the project, not the skin. Presenting the data in the views often requires a lot of customization, but of course Yii 2 helps you bigtime there too with its widgets. But the widgets will have to be the subject of another post.

4. Grow As A Developer. As an individual developer, you build value into your skill set by following best practices. Today you are an individual developer or student. Tomorrow, you may work in a team environment. And those looking to hire programmers are looking for programmers that can follow a discipline and they’re most likely looking for programmers who have framework experience. And the good news is that this is a very accessible framework. You can learn it and benefit from it.

And that gives us the perfect transition to talk about team development. All the benefits that individual developers get from using Yii 2 and Gii are amplified in team and enterprise development. While time estimates are also important to individual developers, they can be absolutely critical in a company environment, where commitments are made to clients or to the backers of a venture.

So you can look at the list of benefits like this:

1. Workflow Standardization. The planning and flow of the project always follows the same path. Team members are assigned specific roles, which is certainly not unusual, but knowing the power of the framework and the capabilities of Gii enhances the strategic deployment of those resources.

2. Common Starting Point For Code. If the conversation starts with data-structure, it will lead to using Gii, in most cases. Obviously there are exceptions to everything. But to the extent that Gii gives us a common starting point for code, it gives the security of building a proven structure. The tight association it creates between model, controller, and view is not something you want to go out of your way to break, unless you have very good reason to do so.

3. Rapid Prototyping. Gii gives you the ability for rapid prototyping. Companies rarely have the luxury of asking “what if?” But with Gii, you can do that. You can even set aside a prototype branch with a separate DB, and playout those whatif scenarios quickly. No company would ever do that unless they could do it quickly and efficiently. But having that ability can give you a competitive advantage, so this is great.

4. Security Of Standardization. Lastly, I should state one of the most obvious benefits to the standardization that both Yii 2 and Gii offer. What if someone leaves the team? Someone else will have to take over their responsibilities, and wouldn’t it be better to know that they can do that efficiently because the structure and discipline of Yii 2 and Gii were adhered to? Of course it would. That’s a big reason why companies use frameworks in the first place.

Besides all the reasons I stated about the benefits of using Yii 2 and Gii, I thought about why it is so good at what it does and why I haven’t seen a competing framework offer something as compelling, at least not from my point of view. And I think the answer is that Yii 2 has it’s own native ORM implementation, which just makes their code generation seemless.

Having their own native ORM also gives Yii 2 the freedom to structure their MVC implementaion how they wish, so they’re able to keep it intuitive, without having to make sacrifices because of 3rd party ORM or other considerations. I believe this is a huge advantage and is one reason why Yii 2 is able to offer so much out of the box. If you haven’t tried this framework, I would strongly encourage you to do so.

I’d like to take a moment and thank all the programmers from around the world who are reading my blog, I hope you are finding it useful. And thanks again to everyone who has supported my book. Feel free to contribute with your own comments, links, and reviews, it is greatly appreciated.

Yii 2 MVC

Happy Holidays to everyone around the world, to our wonderful international following, I hope everyone has a great holiday season. I’ve been hard at work on a new writing project, a new book, which I will be releasing details on in the near future. One of the benefits of constantly doing technical writing is that you get to see things from many angles, which often gives you new perspective, even on the most basic things.

Since my blog is oriented towards beginners, I thought I would share some thoughts about the MVC pattern, and why I think Yii 2 does such a great job utilizing and preserving it. And while I’m mentioning Yii 2, a word of thanks to everyone who has bought Yii 2 For Beginners, I really appreciate your encouragement and support, it helps me vigorously pursue this work.

Ok, so jumping into MVC, it’s such a simple idea in many ways, that it quickly gets diluted, or at least our sense of it, depending on how an application is organized. I’m a big fan of an application having folders clearly named models, views, and controllers. in the basic app, these are very easy to find, right there in the root folder.

In the Advanced Application, which is the one I work with, the application has folders for frontend, backend, and common, and within those folders, you find the model, view, and controller folders. I know I’ve mentioned it before, but it bears repeating, the Advanced Application gives you a working user model, with registration, login, and forgot password functionality as well as the frontend/backend separation that I just talked about, so I actually found that easier to work with than the basic app. Just a heads up if you are relatively new to all this.

So from a basic organizational standpoint, Yii 2 is very intuitive and very well defined. Now I know that might sound a little vague, so let me try to be a little more specific and talk about an advantage that Yii 2 has over many other frameworks.

In Yii 2, you do not have to manually define each route. Yii 2 has built-in routing logic that sends the user request to the appropriate controller and view. By itself, that’s pretty cool, it alleviates you from having to keep track of all the different routes moving through the system as well as it relieves you from constantly having to bounce around to a routes file or equivalent. You don’t have to keep track of the path, so no headaches when there is a typo in the route or you forgot to reference something correctly. You can avoid that entirely, so that’s a plus for Yii 2.

But there’s another big plus from Yii 2’s architecture, and this may be a by-product of Yii 2’s built-in route definition, and that is it gives you a sense of a well-defined MVC right out of the box. You get to see how the controllers interact with the views, how they utilize the models, and how it all fits together. In a sense, the framework itself defines the MVC pattern more strongly, and it teaches you a very efficient and effective structure that you can use as you build out your application.

In the advanced application especially, you get enough examples of validation, form models, and the user model, to really see the MVC pattern operating beautifully. You get just the right amount of logic in the controllers to keep them thin. If you were, for example, to extract too much logic out, so you have almost no logic in the controller, you would be constantly drilling dwon into other classes to keep track of what’s going on. If you have too much logic, the core mission of a controller, which is essentially routing, is lost in clutter. Yii 2 finds the perfect balance for you right out of the box.

Another measure of a successful implementation of the MVC pattern is how little PHP ends up in the view file, always a challenge in modern development. If you look at Yii 2’s implementation of a form view, for example, you will be amazed at how clean it is, and how little is actually there. It’s one of many things I love about the framework.

In the MVC pattern, models are supposed to carry the most weight in terms of volume of code, since they do so much. The models in Yii 2 have been consturcted to push a lot of their logic into the parent classes, which you do not have to write, so you get to focus on setting up your validation rules and relationships. For example, when you create a model in Yii 2 from a table, the model knows the attributes, you don’t have to declare them at the top of the class.

Not only is that convenient, but it also keeps the code clean and gives you a great structure that the models will adhere to. Depending on your level of OOP experience, this might not seem as apparent at first, because, as it is with any larger structure, there’s a lot to get used to. Just the sheer size of the framework can be a little overwhelming, expecially for newer programmers or those with less framework experience.

But learning a new framework always involves taking in a lot of new information, and if you think about it, constant learning is one of the defining characteristics of being a programmer, especially given how quickly things can change. Don’t worry, you are not alone in that, and the good news is that is a lot of support out there for Yii 2. A lot of programmers love this framework.

In the months ahead, I hope to be able to bring you more insights and tutorials that will help get the most out of your experience with Yii 2. Once again Happy Holidays to everyone around the world.

And thanks again to everyone who has supported my blog and book. Feel free to contribute with your own comments, links, and reviews, it is greatly appreciated.

Yii 2 Avanced Template

A question I’ve seen on numerous occasions in the Yii 2 Forum is should I use the Yii 2 Advanced Template or the Basic Install? The answer to this depends quite a bit on what you want to accomplish and how. The first thing to mention is that if you are considering this question, you really should install a copy of both to get a hands on feel for yourself.

The instructions for installation of basic are here in the Guide. The instructions for the Yii 2 Advanced Template Installation is here.

Now if you are familiar with this blog, you know that I’m a big fan of the advanced template and that I use it in my book, Yii 2 For Beginners. It’s a little counter-intuitive, but I actually found that easier to work with than the basic application. The reason for this is that in the advanced template, they provide a fully-functional, database-driven user model, which is out of the box ready to register and login users. You even get the forgot password functionality, working out of the box, so you don’t have to code anything for that either.

So I found this to be incredibly helpful when I was new to the framework and I still feel strongly about it now, it’s a great template. The basic application is awesome too, after all, it’s the same framework. And depending on your application needs, it might make sense to start with that.

In my view, if you are just learning the framework, I think it’s easier to get started with the advanced template, even though you have to do a little more work in configuration and with the second host entry for the backend. Any medium to large size project would probably want separation of backend and frontend areas of the application, so the advanced template gives you a working blueprint for that. And considering it was made by the same team that developed the framework, it’s a strong blueprint. You can learn a lot from it.

Although they give you a working user registration and login in the advanced template, it’s only a starting point, and you still have to implement your own RBAC and any special logging that you might want to do, recording the ip address of the user for example.

Yii 2 does include an RBAC component that you can use with either template, and it is now well-documented and feature rich. I don’t use this implementation in my book, going for something simpler because I prefer to be closer to the RBAC code, so I can modify it more easily. It’s one of those things that just seems like I would have so many custom requirements that it’s just easier to go my own way with it. But that’s not to say anything negative about the Yii 2 RBAC, it’s really cool and ready for you to use if it meets your needs. It’s just another awesome feature that the framework provides for you.

In a sense you could apply the above statement to things like the user model, depending on how you wanted to build your application. So for example, if you had some custom implementation of a user model that was just too different from the advanced template, you could simply build it from scratch with the basic application.

Also, the way the backend and frontend are divided in the Advanced Application is obviously not the only way to do it. Some applications will not require a separate backend, though this is probably a minority. In smaller apps, you don’t necessarily even need a separate set of directories for backend, but keep in mind that apps tend to grow over time, so in my view, it’s best to account for this upfront. The advanced template is perfect for this. But you could also structure your backend differently by setting it up as a module.

Personally, I like the Advanced Template, I think it’s the perfect starting point for a medium to large application, or maybe even a smaller application where there is enough of a backend to imagine managing users through a backend UI.

Another thing I really liked about the advanced template, getting back to what I said earlier, is that you get to see a beautiful implementation of the user model that you can learn from, especially when you are just learning the framework.  For example, did you know that the Yii 2 Advanced Template doesn’t use a password field in the DB?  Instead it uses password_hash, and you can get the full details on that by doing the setup.  It’s just a great example of a user model.

In another example, when I wrote my Super Simple RBAC Tutorial, which gets you a working RBAC for the advanced template in 6 easy steps, I looked at the methods on the User model and the form model and followed their format and it really helped, everything just flowed beautifully. The point being that for newer and beginning programmers, learning how the framework does things is very useful and instructive and will help you progress faster in the long run.

If your are part of a team of professional developers deciding which version to use, basic or advanced, just keep in mind that both are equally capable of delivering enterprise level performance. So it just makes sense to see if the Advance Template represents a good starting point or simply will end up getting in the way, and obviously, no one can answer that question for you, you have to decide that for yourself.

Thanks again to everyone from around the world who has supported my blog and book. Feel free to contribute with your own comments, links, and reviews, it is greatly appreciated.

Yii 2 Test Controller

Welcome back to our beginner’s journey in Yii 2. I’ve made it my mission to help programmers at the beginning stages of framework development to learn about Yii 2, one of the most intuitive and powerful PHP frameworks available.

For those just getting started, I recommend my book, Yii 2 For Beginners, which will take you step by step through setup and onto coding. The book focuses on learning Yii 2 and building a reusable template that can serve as a starting point for your projects. It shows you how to do things, but also explains why we do things the way we do.

This blog serves as an extension of the book, where I share development tips and tutorials that will help you learn more about Yii 2. I also roll out new pieces of the template, which will be incorporated into the book on a quarterly basis. Anyone who purchases the book, gets free updates for the life of the book, so please take advantage of that, if you can.

Today’s tutorial is about implementing a simple test controller to help you with development. This tutorial is for beginning level programmers.

Sometimes in development, you want to isolate a block of code and play with it, without cluttering up your other code. Now version control should always be there if you made a huge mistake, but you really don’t want to be relying on that to step backwards unless you absolutely have to.

So what we’ll do is create a controller named test. We start by navigating to Gii, and clicking on Controller Generator. We don’t have to worry about creating a model first, since we don’t have one, our test controller will be used to play around with different bits of many models, and we will pull in the models via use statements as we need them.

If you don’t know how to use Gii or haven’t started using the framework yet, I would recommend learning that first before moving on to this tutorial. We’re assuming here that you know how to use Gii, which is Yii 2’s built-in code generator.

Ok, so back to the create Controller form on Gii. Pop in test into the first input field to name the controller. We will create just one action for now, Index. Then check to see if the namespace is set to where you want it to go.

In the advanced template, which is what I use because they provide a working user model, I’ve created a test controller for both frontend and backend, though that’s not really necessary. It just helps me when I’m thinking of things to intuitively associate a backend test controller with things I want to try in the backend. Also, sometimes, I leave code in place in the test controller while I’m thinking about whether or not I want to use it.

Ok, so when you hit preview on Gii, it will show two files, the controller and the view file. Once we click generate, it will also create the directory to hold the view file. So let’s do that now.

If all went well, you should have a TestController.php file in frontend\controllers and a frontend\views\test\index.php file.

Yii 2 Behaviors Blameable and Timestamp

One of the things that really made me fall in love with the Yii 2 framework is the intuitiveness of the behaviors method. Behaviors in Yii 2 is a very flexible concept that works on both models and controllers.

On the models, I’ve used two behaviors, timestamp and blameable. Both add a lot of efficiency to the model and prevent code duplication. I’ve talked about timestamp behavior before, I also cover it in my book, so I’ll just cover the basics.

Many times where you create or update a record in the database, you want to keep track of when you did it. This need is so common, that I’m almost tempted to push the behaviors method one layer down by creating my own class extending ActiveRecord and then by having all my models extend from that class. for example:

class MyActiveRecord extends ActiveRecord

 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()'),


So now, if I built all my models to extend MyActiveRecord instead of ActiveRecord, I get my created_at and updated_at fields updated automatically, assuming I have those fields in my DB table. Of course you would have to include a namespace and the appropriate use statements for it to work.

I generally tend not to use this approach, it’s too much for me because not every model that uses ActiveRecord I create will need it, and I prefer to do things the same way every time when I can, even if that is slightly more procedural. For example, I could extend MyActiveRecord when I want timestamp behavior and extend ActiveRecord when I don’t need the behavior. But then I have to keep track of it. Things like that really depend on the size of the project.

If I find there is a lot of code duplication with the behavior at the end of a project, I can optimize, and put the behavior in its own class as in the example. I would rather do it then because while I’m developing, it’s easier for me to get into the flow of the code by seeing the behavior in the same class as the model.

I’m not saying my way is a best practice, just sharing my particular method of doing it. At least now you are aware of some options and can decide for yourself.

Another pre-built behavior that yii 2 has made for you is the blameable behavior, which, when used in combination with the timestamp behavior, looks 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()'),
            'blameable' => [
                'class' => BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',

What blameable does is insert the current user id into the fields created_by and updated_by. This is a super-convient way of doing things. Every time a model gets created or updated, we know who to blame. Don’t you just love the name of the class?

This works out really well for large systems, where multiple users are doing admin and you need to keep track of who is doing what. You can also use this for frontend implementations, for example if you had a posts table and you wanted to use this method to keep track of the author. Alternatively, you could set that in the controller, but the behavior relieves you of having to write any additional code. This is extremely efficient, easy to implement, and easy to understand the benefit.

Now if I were writing a lazy tutorial, I would stop there. However, it’s worth noting that to extract the blameable username and display it, we need 4 additional methods on our model and the Yii 2 guide on behaviors does not mention them. Since this is not from the guide, please keep in mind that this is my way to do it, not necessarily official, and there may be a more concise way to do it that I’m not aware of.

However, until the docs are more complete, I had to come up with my own solution, which I’m pretty happy with at this point. I’m a big fan of these one line methods, which the Yii 2 guide does suggest using for relationships, so that’s how I approached this.

I simply created a get method to map the id field of user to the created_by field of the current model. Then in the next method, getCreateUserName(), we can access the username using the magic get syntax in a ternary statement:

public function getCreateUser()
    return $this->hasOne(User::className(), ['id' => 'created_by']);

       * @getCreateUserName

public function getCreateUserName() 
    return $this->createUser ? $this->createUser->username : '- no user -';

I put in a condition for – no user – even though the blameable behavior will fire everytime and update to the current user. It doesn’t hurt to code in the possibility that there is no id stored, and in such a case, we return the string ‘- no user -‘. It would help you troubleshoot at the least.

Of course we had to do the same methods for updated_by, so that required 2 more methods.

public function getUpdateUser()
   return $this->hasOne(User::className(), ['id' => 'updated_by']);
       * @getUpdateUserName

public function getUpdateUserName() 
    return $this->createUser ? $this->updateUser->username : '- no user -';

I also had to add the following to my attribute labels method on my model:

 'createUserName' => Yii::t('app', 'Created By'),
 'updateUserName' => Yii::t('app', 'Updated By'),

And once you have those labels in place, you can use them in a view like so:

 <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            ['attribute'=>'createUserName', 'format'=>'raw'],
            ['attribute'=>'updateUserName', 'format'=>'raw'],
    ]) ?>

Don’t worry about the rest of the example, that is my Faq model in the DetailView::widget. Ther relevant lines are:

 ['attribute'=>'createUserName', 'format'=>'raw'],
 ['attribute'=>'updateUserName', 'format'=>'raw'],

Those labels reference our get methods, using magic syntax, which means the get is implied, not explicit and you have to make the first word lower case. So now, instead of getting an id number displayed, we get the actual username. Cool stuff.

You can see that when we talk about implementing things, we have to jump around a bit. We went from behaviors on the model to calling a get method on the view, so we can return the username instead of user id.

Controllers can also implement the behaviors method, and this is incredibly useful for access control. I did a complete tutorial on RBAC using behaviors on the controllers, you should check that out if you want to continue on to see how you can use behaviors that way. I made implementing RBAC pretty simple, boiling it down to six easy steps.

I also cover this topic more extensively in my book, Yii 2 For Beginners.

Well, that’s it for this tutorial. Thanks for reading and thanks for your support. Feel free to add your comments and thoughts, it’s appreciated, as are links and reviews. Thanks again.

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.