Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This tutorial has a new version, check it out!

Starting in Symfony2: Course 2 (2.4+)

1:50:44

What you'll be learning

// composer.json
{
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "~2.4", // v2.4.2
        "doctrine/orm": "~2.2,>=2.2.3", // v2.4.2
        "doctrine/doctrine-bundle": "~1.2", // v1.2.0
        "twig/extensions": "~1.0", // v1.0.1
        "symfony/assetic-bundle": "~2.3", // v2.3.0
        "symfony/swiftmailer-bundle": "~2.3", // v2.3.5
        "symfony/monolog-bundle": "~2.4", // v2.5.0
        "sensio/distribution-bundle": "~2.3", // v2.3.4
        "sensio/framework-extra-bundle": "~3.0", // v3.0.0
        "sensio/generator-bundle": "~2.3", // v2.3.4
        "incenteev/composer-parameter-handler": "~2.0", // v2.1.0
        "doctrine/doctrine-fixtures-bundle": "~2.2.0", // v2.2.0
        "ircmaxell/password-compat": "~1.0.3", // 1.0.3
        "phpunit/phpunit": "~4.1" // 4.1.0
    }
}

Over the next hour, we're going to take you through some of the most difficult areas of Symfony learning all about security, forms, and parts of Doctrine. We'll also see testing and learn more about how Symfony's service container works. When you get to the end, you'll be well on your way to mastering Symfony.

One of the things we'll be creating is a security system that stores users in the database. This is functionality similar to what's offered by the very popular FOSUserBundle. That bundle is really great, but until you understand how the security system works, you're going to run into limitations. Once you do, you'll feel at home using FOSUserBundle or configuring the security system all on your own.

Highlights:

  • Learning and building a form-login security system from scratch
  • Loading users from the database
  • Using AdvancedUserInterface and UserProviderInterface classes to give us more control over login
  • Doctrine Repositories and Querying
  • Building forms: creating fields, the data_class option, form type classes
  • Form field options & HTML5 validation
  • Form rendering
  • Functional Testing!

... and of course, tips, tricks, best practices and other little features along the way!


Your Guides

Ryan Weaver Leanna Pelham

Buy Access

Join the Conversation?

151
Login or Register to join the conversation
Default user avatar

Hi ! great tutorial so far, but I've face some problem with the code you using to customize the user provider, which you copy and pasted it in the tutorial vid. But it was off the screen, i 've no idea where can i get these code in order to resume my study on this great framework !

I need the code in refreshUser() and supportsClass() in the UserRepository.php, : ) thanks

1 Reply
Default user avatar

Oh right above these comments ! sorry, i've found that ! :P

Reply
Default user avatar

@Jai I expect you have overcome this by now, but all you needed to do was copy the {% block stylesheets %} block and it's contents from EventBundle/Resources/views/layout.html.twig to the app/Resources/views/base.html.twig

1 Reply
Default user avatar

For the register form creation is there supposed to be another .css file? Currently, I am re-using the login form to use that template as it somewhat matches the video, I haven't spotted anything in the downloadable code.

<section class="main-block">

1 Reply

Hey keefekwan!

Yes, there is a CSS file missing, which means that if you're coding along, the registration form works fine, but doesn't look as nice as in the screencast. Thanks for catching that! I've opened up an issue and we'll fix it and make it look pretty again for the next version: https://github.com/knpunive...

Cheers!

1 Reply

Thanks for commenting on this. I ran into the exact same problem and was wondering the exact same thing. My css skills are still on the new side, so hopefully 2.4+ comes out soon. :P

Reply

Actually if you take the login.css file and copy the text into a register.css file and replace .login with .main-block you end up with something that doesn't look entirely terrible. Particularly if you just want something that will get you through the tutorial.

Reply
Default user avatar

Hello Big Guys!

First of all thanks for the good tuts!

I'm currently on part 3 of Starting in Symfony lessons, (Proud of my
decission on following ALL your tutorials!!) , everything goes smooth,
since i am coding along with you, but since the second round I noticed that everytime I tried to save an
event on my project ( Route: http://127.0.0.1:8000/new), let me explain you....I fill out
all the fields and click save event button...and I got this ugly exception:

"No route found for "GET /create": Method Not Allowed (Allow: POST)"
405 Method Not Allowed - MethodNotAllowedHttpException
1 linked Exception:

MethodNotAllowedException »

I looked back through all the possible causes and files, I've challenged myself
to find the answear, googling, discarding, I compared them with
yours....I made some test changing things on my event.yml file, but the
problem persist.

( HERE IS THE PART OF MY CODE I THINK IS THE RESPONSIBLE OF THE ISSUE:

event_create:
path: /create
defaults: { _controller: "EventBundle:Event:create" }
requirements: { _method: post }

)
Apparently is ok!!
On php app/console router:debug all routes looks fine........

Any hints or recommendations? I appreciate your time on giving me a hand!

Thanks!
Edison

1 Reply

Hi Edison!

So glad to hear you're going through all the tutorials - you won't regret it :).

A few things about your situation:

1) Most of the time, routes match only on URL. If you have a route whose path is /create, then if you go to /create, it will match. Good work on using router:debug to investigate this.

2) Sometimes - and this is totally optional - you might decide to say "Hey, I'd like /create to only match on POST requests" (e.g. form submits). That is what the "_method: post" thing in the route is doing. This means that if you go directly (e.g. by just putting /create in your URL and hitting enter) to the URL, you will get this "Method not allowed" exception. You have matched the URL, but this URL only allows POST requests, and you are using a GET request.

3) Why is this happening in your case? Well, since this is a form submit, you probably *do* want to respond to only POST requests (though in practice, if you also allowed the route to respond to GET requests, it would simply look like the user filled out the form blank and submitted - so they would get validation errors and the form would re-render, so no big deal). My guess is that you're missing the method="POST" part of your <form> tag, which is causing the form to submit via GET, causing this error.

I hope this helps you discover discover your issue.

Cheers!

Reply
Default user avatar

YESSSSSSSSSSSSSSSSS! You are the Best! Haha wow. :)

1st. Thanks for your rocket answear, you always do that!
2nd. You solved my problem, you were right, in my <form> tag was the solution!

Cheers!

Reply
Default user avatar
Default user avatar Shairyar Baig | posted 5 years ago

A good refreshing tutorial. Can't wait to go through the next part.

1 Reply
Default user avatar

Love the videos guys, really speeding ahead with Symfony2. What an awesome framework, I love it!
Any updates on the third episode? That's the one I really want to see (services, best practice) and will purchase on release. Cheers!

Reply

Hey James!

Aw, I'm really really happy to hear about your success. The third episode will hopefully be done within the next week and a half. BUT, it's a free upgrade, and the differences should be pretty small - so if we're holding you up, I'd go ahead and grab episode 3 now :).

Cheers to you!

Reply
Default user avatar

Hey Ryan,

Any updates on the 2.3 screencast?

Reply

Hi James!

We've just updated Episode 3 with the new, much nicer format and updated it for 2.2. We'll also do the same for episode 4 this week. The updates for 2.3 will come after that :). But, again, don't wait - there fortunately haven't been that many changes with the new versions of Symfony (mostly new features, that are outside of the project we're building). When we do update, we'll point out some new feature and some other small changes. That's nice, but not worth waiting for if we're making you wait.

Cheers!

Reply
Default user avatar

Awesome Ryan, *insta-purchase*, thanks! :)

Reply
Default user avatar

Hi Ryan,

Great work! It's clear and easy to understand tutorial!

But I think, there's a typo in "message" for $plainPassword field, at "Basic Constraints and Options" section. It should be "Please use at least onE upper case letter ...", with "one" instead of "on". Isn't it?

Reply

The fixes (https://github.com/knpunive... are up on live on the site! Woo - thanks!

Reply
Default user avatar

Ryan,

I've found next typo in "After-dinner Mint" at "Whitelisting: Securing all Pages, except a few" section.

It should be 2x:
- { path: ^/ , roles: ROLE_USER }

Instead of:
- { path: ^/create , roles: ROLE_USER }

Reply
Default user avatar
Default user avatar frimousse | posted 5 years ago

Hi I recently bought all the Symfony lessons. I had no problems with lesson 1 but in lesson 2 whenever I press 'login' after entering 'user' and 'userpass' I get a {no route found for "GET /"}. I cannot see any differences with my code and the one on the files distributed with the lesson. After pressing 'login' the address on top of the browser is "http://myhost/web/app_dev.php/". Shouldn't the login button sending me to "http://myhost/web/app/event" if the login is succesful or "http://myhost/web/app/login" if the login is unsuccessful? I've been trying to fix this for two days now. Frustrating...

Reply

Hi there!

Sorry for the issues, but we can definitely get things working :). A few things:

1) The issue from going from episode 1 to episode 2 is actually do to a minor change that we made between episodes 1 and 2 to the routing. It's a small change, but if you're following straight from episode 1 to 2, then some URLs will have changed. We should

Sorry for the issues, but we can definitely get things working :). A few things:

1) The issue from going from episode 1 to episode 2 is actually do to a minor change that we made between episodes 1 and 2 to the routing. It's a small change, but if you're following straight from episode 1 to 2, then some URLs will have changed. We'll be fixing in the future - so apologies. What you should do is download the code for episode 2 and use the "start" directory as your new starting point. For example, in episode 1, you have URLs like `/event`, but in episode 2, that same page is actually at `/`.

2) More broadly, Symfony follows some very specific (and configurable) rules after a successful login. Some of it is explained here: http://symfony.com/doc/curr.... But basically, it tries to redirect you to the last page you tried to visit before hitting the login page. If there isn't any (i.e. you clicked directly to the login page), then it falls back to just "/". If that's not what you want, that's configurable in a few ways (shown in that entry).

Hopefully this gets you going again! If you have any other issues, just ping us here :).

Cheers!

Reply
Default user avatar

Hi Ryan, Thanks for this. I struggled so much with it and tried so many different things to get it to work that I probably messed it up more than I helped. In the end, I scraped everything and restarted lesson 1 from the beginning to have a 'clean' copy. I saw what you mentioned about the "/event" becoming "/" and I made the change - just about to restart lesson 2 now. I don't know how close you are to Fabien Potencier but I would suggest that the file routing.yml in app becomes approuting.yml which would distinguish it from the bundle routing.yml file and avoid some potential confusion.
Regards.

Edit 1
Still does not work with the change. What I do is I listen to the video, pause it and do all the changes as they appears on the screen (basically I do every click she does and expect to see the same page, errors, etc). Right now, the lesson breaks down at 9:10. First, I'm losing the background - I have the login form on the top left on a blank white screen (seems like it cannot find the '::base.html.twig'); second on typing user and userpass, I get a link to "/" which shows me the event page whilst the video shows the /new page. If I press "create new event", I get: An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "event" as such route does not exist.") in EventBundle:Event:new.html.twig at line 6. And of course it does not exist because I changed it to "/" to make the first part of the program to work.

I guess progressing throught the lessons(even with the above-mentioned change) is not an option and for the sake of not wasting too much additional time, I will resort to copy the 'start' files' and see if I can get this to work. That said, it is not very helpful if you cannot continue from where you left because, as a beginner, it is not evident what parts have been changed in the background. (also, not your fault obviously, but the error messages are hardly helpful: an error message on line 1883 on a class that I have never seen does not really tell me where is the problem)

Additional notes: Using the start files is also not straightforward as you have the JMS security bundle in the AppKernel.php and nowhere in lesson 1 or 2 these files are used. Not hard to remove from the kernel but just copying the files will generate an error as the bundle won't be found.

System: Windows 7 64 bits with IE9.

Edit 2

To use the 'start files' you will have to:
1- delete any references to JMS in the AppKernel.php
2- delete any references to JMS in the security.yml
3- delete reference to trust_proxy_headers in the config.yml

Once you've done that, you now access your application with ".../web/app_dev.php/" instead of
".../web/app_dev.php/event"

Reply

Hey there!

Ok, let's see if I can help out :).

1) The missing assets aren't a missing or not-found "::base.html.twig" - if that file is missing, you'll get a big error. Instead, I think your CSS files just aren't being loaded. Be sure to run this command:

php app/console assets:install

Normally, this is run automatically for you when you run "php composer.phar install", but the very first time you run that command, it may fail right at the end if you haven't already copied app/config/parameters.yml.dist to app/config/parameters.yml. That's actually totally fine, but make sure you run the above command, it'll probably fix your CSS files :).

2) Yes, a few things change between episode 1 and episode 2 - that's something we'll fix in the future. Until then, use the "start" directory from episode 2 to work from. The changes between the episodes are actually pretty minor: we added some stylesheets and tweaked the names and paths for a few routes. That's not much, but it is enough to mess you up and give you the errors you're seeing - so apologies!

3) I was able (just now) to download the "start" directory for episode 2 and get things running without any issues. You're right that we don't use the JMSSecurityBundle, but it is included in the composer.json file and downloads just fine. Based on what I'm seeing, it almost looks like you upgraded your Symfony app to Symfony 2.3, in which case the JMS stuff is *not* included, and you would need to remove the trust_proxy_headers. That's fine, but hopefully it helps to know why that error would be happening :). If you use the "start" directory, you'll get a copy that will work just fine.

Cheers!

Reply
Default user avatar

Hello!

I have same problem: I have seen in video 2
".../web/app_dev.php/" is showing event list, but in episode 1
".../web/app_dev.php/event" did that, so I tried to change my code to do
exactly as the code in episode 2 does, but no results. Then I tried to
copy the code from "start" folder from episode 2, no results again -
blank page have been showed then.(I also tried all the steps below Edit
2)

I really like all these courses and I would like to learn a
lot from them, but I can`t continue lesson if I have this problem. Is
there any solution for this problem?

Best regards.

Reply
Default user avatar

Hi, by copying all the files from the Start directory and doing the modifications mentioned in EDIT 2 above (assuming Symfony version 2.3.6) you should be able to follow just fine. I have not finished it yet due to time constraints but so far I am a third through it and everything is exactly as in the video. From where I am now in the video all the 'routing issues' are now dealt with as it is now moving into loading users from the databse. Do not copy just a few files here and there, replace whole directories (app and src) all at once (it'll also save you a bit of typing along the lesson!). Best!

Reply

Great advice frimousse! frimousse when you start using the "start" directory, are you still accessing the site via by hitting the "app_dev.php" file in your browser? That's very important - because if you don't execute this file, you're executing Symfony in the "prod" environment, and Symfony doesn't show you those errors (which could cause you your white screen problems).

To be sure, one trick you can do (if you have PHP 5.4) is to use PHP's built-in web server. From the command line at the root of your project, try:

php app/console server:run

Then, you can access your site via "http://localhost:8000/app_dev.php". See if this helps out. And if not, feel free to ping back here or email me directly (ryan@knplabs.com) and I'll make sure we get things working :).

Cheers!

Reply
Default user avatar

I have always avoided Symfony in the past because none of the tutorials I tried (I'm not suggesting I've tried all of them) worked; there is always some vital detail or details missing and if you're a newbie you have no chance. Anyway, these Knp videos are fantastic and if I use Symfony2 on my next be project it will be because I them. However, the setup changes from video 1 to video 2 were pretty aggravating and best avoided in future.

The advice to copy the start folder is good, but must be done with care as you can end up losing some of your files which aren't in the new start folder if you simply replace the top level app folder with the new one. I realised this too late and found the easiest solution was to redo Lesson 1, which, on the positive side, was probably a good learning reinforcement exercise.

Also, the EventBundle\Resources\views\layout.html.twig file is missing the stylesheet block from lesson 1, so make sure you keep your old lesson 1 files somewhere so you copy this back in.

{% block stylesheets %}
{% stylesheets 'bundles/event/css/*' filter='cssrewrite' %}
<link rel="stylesheet" href="{{ asset_url }}"/>
{% endstylesheets %}
{% endblock %}

Reply

Hey Rob!

Thanks for the comment - I really appreciate it! We try really hard to make these tutorials full and complete :). Of course we have this pesky episode 1 to episode 2 transition issue - so sorry about that!

Because of that, I want to make sure everyone is able to get things working. By using the "start" directory from the code download as your starting project before coding with this tutorial, you should be just fine. This means using all of the contents of that directory in place of the project you built in episode 1. In reality, there aren't that many things that changed between episode 1 and 2, but just to be safe, use the "start" directory as your new project.

About the stylesheets in "EventBundle\Resources\views\layout.html.twig" - these were just moved to app/Resources/views/base.html.twig. So you shouldn't need to re-add them to layout.html.twig. But do be careful: if you override the "stylesheets" block in any of your templates (e.g. layout.html.twig or index.html.twig), you'll completely replace the stylesheets from base.html.twig, unless you use the parent() function (see: http://symfony.com/doc/mast....

If anyone has any issues with using the "start" directory in the code download, you can keep pinging us here. I have re-tried it a few times, and everything works perfectly without making any changes. Though if you do have problems, we can work through them together :).

Cheers and thanks!

Reply
Default user avatar

Sorry, I guess I didn't copy across the new base.html.twig file, and perhaps I was wrong about the app folder. Regardless, it ended in a mess for me; perhaps because I tried to fix it before seeing some of the advice in the other comments on this page and I just made things worse.

I don't want to be negative though, these really are good tutorials. Thanks for making them :-)

Reply
Default user avatar

These are great, but as Rob said, there's some really annoying problems. Another one is that it hasn't been updated to use an available version of bootstrap, so it looks wrong. When was the last time you guys actually went through them from the start? It would really help if you did and just wrote some update notes (and updated a couple of little bits of code where needed) so that people could follow them and get everything working perfectly.

Reply

Hey @Ant!

These are awesome ideas - we're planning now on how we can show changes or notes to you guys when things (like versions of Twitter Bootstrap) change. Like right now, everything still works fine from start to end, but you'd need to go find the old version of Twitter Bootstrap to match the markup.

To that end, would you have a few minutes to chat about this? I'd like to hear you (or anyone's experience) and see exactly what things we can do to make things the clearest. I don't have your email, but if you do have some time, please email me at ryan@knplabs.com!

Thanks for the comments!

Reply
Default user avatar

Also, just a thought, could be good to have a version of the app running online so people can check their html markup against it. Could help diagnosing issues.

Reply
Default user avatar

Or 4 versions, one corresponding to the end of each screencast

Reply
Default user avatar

Hi, I have an issue with functional testing. It works exactly as in the video when testing the register page for the presence of the word "Register". But when I add the second test (submitting a blank form with $client->submit($form); ) the page HTML gets printed out to the terminal and no tests are run. If I comment out the first set of tests (for the presence of the word "Register"), the form test works as expected, so it doesn't seem to be a syntax issue. I also tried using the downloaded code as another check against typing errors, but the same thing happens.

I have tried Googling for an answer, but to no avail. I'm using Symfony 2.3. Are there any obvious 'gotchas' I'm overlooking?

Reply

Hi Rob!

Hmm, that does sound odd, but I'm sure we can debug it and figure out what the issue is! Can you open up an issue here: https://github.com/knpunive... and maybe include a screenshot of what it looks like when you run the tests in the different scenarios?

Thanks!

Reply
Default user avatar

Hi Ryan, thanks for your offer to help. However, I have resolved the problem.

I re-installed phpunit to make sure all the paths were correct (I'm using MAMP Pro) and updated the phpunit path in the PhpStorm project config. This seemed to fix the initial problem, but I then had an internal server error to do with templating (although the page worked correctly in the browser). After much faffing about, clearing the cache, restarting MAMP and restarting PhpStorm it suddenly started working correctly.

Reply

Awesome, cheers Rob!

Reply
Default user avatar

Great Tutorials!
Just as a note:
- { path: ^/new, roles: ROLE_USER } doesn't work.
- { path: ^/event/new, roles: ROLE_USER } is the right one.
symfony (2.4)

Reply

Hi Nick!

This is because some routes changed slightly between episode 1 and episode 2 of our series. For example, /event/new changed to be just /new in episode 2. So, sorry about that confusion :). There are a few other related comments on this thread about those minor changes.

If you are coding from episode 1 to episode 2 directly, there are a few changes you'll need to make to your code, which I have documented here: https://github.com/knpunive....

If anyone has any issues, don't hesitate to ask!

Thanks!

Reply
Default user avatar
Default user avatar Mathias Strasser | posted 5 years ago

Hi,

I've juste buy the lesson 2.

I don't know why but I've a blank page with this messages :
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest". [] []
[2013-12-19 13:43:07] request.INFO: Matched route "event" (parameters: "_controller": "Yoda\EventBundle\Controller\EventController::indexAction", "_route": "event") [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener::onKernelRequest". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\Fragment\FragmentHandler::onKernelRequest". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DeprecationLoggerListener::injectLogger". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector::onKernelController". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.controller" to listener "Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelController". [] []
[2013-12-19 13:43:07] doctrine.DEBUG: SELECT t0.id AS id1, t0.name AS name2, t0.imageName AS imageName3, t0.date AS date4, t0.location AS location5, t0.details AS details6 FROM yoda_event t0 [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\FirePHPHandler::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\ChromePhpHandler::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\CacheListener::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\Fragment\FragmentHandler::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse". [] []
[2013-12-19 13:43:07] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener::onKernelTerminate". [] []

I've just beginning the first modification (firewalls) in security.yml, this to work, so I went to the second part (access_control) and then I got a blank page.
I returned with the original file and I still do not display, I do not understand.
Can you help me on what exactly happens?

Reply

Hi Mathias Strasser!

A blank page is very strange, and Symfony should at least be giving you an error page. It's probably some small misconfiguration. Can you open up an issue here: https://github.com/knpunive... Then we can work together to see what the problem is :). Obviously, double-check to make sure that you're executing the `app_dev.php` script, so that you see errors. Also, check your `php.ini` configuration to make sure that `display_errors` is set to true so that PHP errors are showing up.

Cheers!

Reply
Default user avatar
Default user avatar Mathias Strasser | weaverryan | posted 5 years ago

Thanks in advance :)

github.com/knpuniversity/sy...

Reply
Default user avatar
Default user avatar nglaser power | posted 5 years ago

Use $form->handleRequest instead of bind. I am talking about register form video in the series.

Reply

Hi nglaser power

Yes, you're right :). Both bind() and handleRequest() work, but bind() is deprecated. Fortunately, it won't be removed from Symfony until version 3.0.

But, we do want to keep that updated! I've opened up an issue to track that change and any other form-related changes we may need: https://github.com/knpunive...

Thanks so much!

Reply
Default user avatar
Default user avatar Mathias Strasser | weaverryan | posted 5 years ago

Hi,

Now, bind redirect to submit.
So why use handleRequest ?

Reply

Hey Mathias!

Yes, there were actually 2 changes to bind:

1) bind was renamed to submit
2) Passing a Request object to submit was deprecated. It's still completely valid to pass an array of data to submit (that's its purpose), but if you want to pass a Request object, use handleRequest. The reason for this second change was performance - one function for handing processing the Request object (handleRequest) and another for handling data arrays (submit).

The big takeaway is to use handleRequest almost always. The only exception is if you are passing the array of POST data directly (pretty uncommon), then use submit(). We'll be working to update this screencast with the latest and greatest over the next several weeks too :).

Hope that clarifies!

Reply
Default user avatar
Default user avatar nglaser power | posted 5 years ago

Also in order for the user to be authenticated you have to call the setRoles function when you create the user.

Reply

Hi again nglaser power!

Do you mean calling $user->setRoles() on the fixtures? It *is* true that User::getRoles() must return at least 1 role in order for you to be authenticated after logging in as that user. However, in our implementation of getRoles(), we *always* return at least ROLE_USER, even if the roles property is actually empty in the database. So, you shouldn't need to call setRoles() in the fixtures - having empty roles is ok - you'll always at least have ROLE_USER :). Reference: http://knpuniversity.com/sc...

Are you seeing something different?

Thanks!

Reply
Default user avatar

Awesome video. Just a quick question, what is the actual difference between an entity and repository? More to the point, should I ensure that all custom functions I write (ie: code that is not auto-generated when I update my entity yml file) be stored in a repository while all the auto-generated code that is done by doctrine and Symfony (so far it looks like just the getters and setters for the POPO file) be stored in the entity file?

Reply

Hi John!

Think of an entity as representing each row in a table. Assuming you have a Product entity class, if you create a new Product object and save it, that creates a new row in the product table. When you query for 10 products, you get to Product objects.

Think of the repository as the class that holds query logic. You create methods on your ProductRepository class, for example, like "findAllAlphabetical" that make a query to return some Product objects.

So to your question, you'll likely write custom code in both your entity and your repository. If you need make a new query, create a new function in your repository that queries exactly how you need. But when you're getting information about 1 specific row in some table (e.g. a Product), then you might add a new function to your entity. For example, imagine I have a BlogPost entity with a publishedAt field, which is set to the DateTime when the BlogPost should become published. If it is a date in the future, then it's not published yet. As a convenience, you might create a new function inside your entity called isPublished, which looks something like this:


public function isPublished()
{
    // check if the publishedAt is in the past
    return $this->publishedAt < new \DateTime('now');
}

This custom code is concerned entirely with the data from this 1 BlogPost, so it fits nicely in the repository.

Hope that helps out a bit!

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

userVoice