Starting in Symfony2: Course 1 (2.4+)

UPGRADE! Check out the newest version of this tutorial

Get your first Symfony2 project off on the right foot, with the right tools, best practices and tips. If you're serious about getting into Symfony2, this course is for you!

In this screencast, we start building a real events application from the ground-up, touching on and discussing the most fundamental parts of the application. Specifically, we'll cover:

  • Installation, Git and Setup
  • Composer
  • Routing
  • Controllers
  • Introduction to the service container
  • Twig
  • Doctrine
  • Server setup
  • Code generation
  • Fixtures & external libraries
  • And other tips and tricks

Your Guides

Ryan Weaver Leanna Pelham

Questions? Conversation?

  • 2016-06-24 Victor Bocharsky

    Hey, Sudhir!

    We're sorry, your message was marked as spam, I've just approved it.

    Do you try to use Symfony Web Debug Toolbar to debug sent emails? You possibly need to enable to redirect interception, check Viewing from the Web Debug Toolbar. But actually, if you got "true", but the message not delivered, that means you have some misconfiguration of your swiftmailer (i.e. wrong SMTP credentials etc.) or probably your mailer server, which is apptix mail server, has wrong configuration.

    BTW, take a look at Mailcatcher. I don't use it by myself, but looks like it should help you.

    Cheers!

  • 2016-06-24 weaverryan

    Hey Sudhir!

    Hmm, ok:

    Error 1: It looks to me like some bad data has been somehow put into your roles column in the database. This column is an array, that's been serialized to a string. Doctrine is trying to deserialize it, but the data is invalid. Check this out: http://stackoverflow.com/quest...

    Error 2: You're getting the very unhelpful "500 Internal Server Error" because you're in the "prod" environment. So, something is likely broken, but we can't see the error :). Make sure to put the app_dev.php in the URL - then you should see a proper error message.

    About PRE_2, It looks like you've forgotten to render the authentication error in login.html.twig - so it is likely that there *is* a problem logging in, but you're just not displaying the message. Check out the template in this page: http://knpuniversity.com/scree... - notice we're rendering an "error" variable.

    Cheers!

  • 2016-06-20 Sudhir Gupta

    Hey weaverryan ,

    I tested as per your suggestions. here is the list what i make the changes.
    IN PRE1-:
    i enable the encoders

    security:
    encoders:
    FOS\UserBundle\Model\UserInterface: bcrypt

    after doing that am getting an error. Here i has posted the snapshot (Error 1).
    Also when i go to register page and hit the register button after filling the form. i am gettig "500 Internal Server Error". see Error 2
    Error 1-: https://goo.gl/oTkWts
    Error 2-: https://goo.gl/usmjna

    ------------------------
    Now in PRE_2
    when i am trying to login, its redirecting me to same login page. i think validation process is not being completed.

    here is home page code

    /**
    * @Route("/", name="homepage")
    */
    public function indexAction(Request $request)
    {
    // replace this example code with whatever you need
    return $this->render('default/index.html.twig', array(
    'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..'),
    ));
    }

    i am strange that why same code is running at your end but not me. ( i cleared cache. i checked log too but nothing wrong i detect)

    Do you have any fully functional login and logout test application. if yes.. pls provide.

    Thanks and hoping to hear soon.

  • 2016-06-18 weaverryan

    Hey Sudhir!

    I see your code and was able to get it running. But now, I'm not sure exactly what the problem is with PRE1 and what the problem is with PRE2. In other words, what specific problems are you having?

    I can tell you a few things, however:

    1) In PRE_1, the "encoders" key in security.yml should be uncommented, or else you can't create users or login. After doing this, I *was* able to login
    2) In PRE_1, the access_control entry ^/admin/ will NOT be activated when you try to go to the /admin URL. In other words, if you go to /admin and expect that access_control to be matched and require ROLE_ADMIN, you're incorrect. The ^/admin/ access_control matches /admin/*, but it will not match the URL /admin (because there is no "/" at the end). If you want that access_control to match your /admin page, change the access_control to simple ^/admin
    3) In PRE_2, if you look at your access_control, you will see that you have correctly configured your access_control to require login on EVERY page, except for /mouse*, /login*, /register* (and the debugging URLs). This explains why you can go to "/mouse" anonymously, but you cannot go to the homepage ("/") until you are logged in. Internally, when you go to /mouse, Symfony matches the first access_control only, and because you have IS_AUTHENTICATED_ANONYMOUSLY, you are granted access. But when you go to "/", you match the *last* access_control only, and this requires ROLE_USER.

    Again, let me know what specific questions you have - I'm a little lost as to what is and is not working as you expect :).

    Cheers!

  • 2016-06-16 Sudhir Gupta

    pls also see this comment

    https://github.com/sudhir500/S...

  • 2016-06-15 weaverryan

    Hi Sudhir!

    Yes, I know the "The connection was reset" error - you're likely caught in a "redirect loop". This happens when you try to access a protected page, so Symfony redirects you to /login. But, for some reason, /login *also* requires you to be logged in, so Symfony once again redirects you to /login. This continues until your browser gives up.

    With your first security.yml configuration, I would *not* expect this behavior: your ^/login access control with IS_AUTHENTICATED_ANONYMOUSLY guarantees that the /login URL is available without needing to be logged in. However, I *would* change this to ^/login, instead of ^/login$ - because usually the login form submits to /login_check, which also needs to be public (but this is not causing your current problem). So, I don't see how you could get this problem if you have the PRE 1 security.yml configuration.

    About PRE 2, you have no access_control, so I also don't see how you could get the error in this situation.

    So unfortunately, I still can't find the issue! Also, PRE 1 and PRE 2 are very different security.yml files - are they from the same project? I wasn't sure what these files represented :). If you're able to post a simple version of your project to GitHub, we could debug this very easily. I suspect something subtle is wrong :/.

    Cheers!

  • 2016-06-15 Sudhir Gupta

    Hi weaverryan ,

    Here is my security.yml

    PRE 1
    # app/config/security.yml
    security:
    #encoders:
    #FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
    ROLE_ADMIN: ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
    fos_userbundle:
    id: fos_user.user_provider.username_email

    firewalls:
    main:
    pattern: ^/
    form_login:
    provider: fos_userbundle
    csrf_token_generator: security.csrf.token_manager
    # if you are using Symfony < 2.8, use the following config instead:
    # csrf_provider: form.csrf_provider

    logout: true
    anonymous: true

    access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN }
    - { path: ^/(css|js), roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/(_wdt|_profiler), roles: IS_AUTHENTICATED_ANONYMOUSLY }

    But when i use alternate method using this security.yml. i am able to login, but here i am getting another problem.
    only three url ("/","/login" and "/logout") is working. no other url is working. when i hit another url. its taking lot of time and finally i get timeout error msg.

    PRE 2
    security:
    encoders:
    AppBundle\Entity\User: bcrypt
    providers:
    database_users:
    entity: { class: AppBundle:User, property: email }
    firewalls:
    # disables authentication for assets and the profiler, adapt it according to your needs
    dev:
    pattern: ^/(_(profiler|wdt)|css|images|js)/
    security: false

    main:
    anonymous: ~
    guard:
    authenticators:
    - app.form_login_authenticator
    logout:
    path: /logout
    target: /

    snapshot of error-: http://postimg.org/image/52qvo...
    security.yml for (FOS) #pre1 http://postimg.org/image/mil1q...
    security.yml for #pre 2 http://postimg.org/image/fe38h...

  • 2016-06-14 weaverryan

    Hi Sudhir!

    1) Hmm, there is probably an issue with the password encoding, but it could be something else. "Invalid Credentials" by the way, could also mean that you have an invalid username - for security purposes, Symfony always says "Invalid credentials", even if the problem is that the User was not found. I would try manually creating a user through the command line (https://symfony.com/doc/master... to see if this helps with any password encoding problem. If it doesn't help, tell me if you have any other customizations (e.g. a custom user provider). If you post your security.yml, that will help :).

    2) This depends on how you want to do it. You have 2 options (and you can combine them): access_control in security.yml or by denying access in your controller. By default, if you do nothing, all pages are public. Check out https://knpuniversity.com/scre... and https://knpuniversity.com/scre... for some strategies here. If you're using Symfony 3, on the first page, replace "security.context" with "security.authorization_checker" when you write the code. If you simply want to check if the user is logged in, you can look for ROLE_USER (this is a role given to all users by FOSUserBundle).

    P.S. Your labels will start to be translated into English if you enable the translator in Symfony - check out https://symfony.com/doc/master...

    Cheers!

  • 2016-06-14 Sudhir Gupta
    Update
    Hi weaverryan,

    I create login / logout system with user_role as described in docs.
    i used FOSUserBundle.
    everything seems perfect. i am getting a login screen but when i tried to login, i am getting error message "invalid credentials"
    i am using username and password which is stored in in mysql, password is encrypted in bcrypt
    (of course password will be normal text i.e bcrypt decrypted ).
    But still no luck..

    2nd question,

    If i would able to login then how i will validate that, page "A" should be access by logged user only but Page B by everyone (even without login).
    i hope you will help me.

    Thanks in advance weaverryan

    Here is snapshot-: http://postimg.org/image/pho6relvb
  • 2016-06-10 Sudhir Gupta

    i have to try both things..
    will let you know when i done.
    however thanks u very much for your prompt reply..

  • 2016-06-09 weaverryan

    Hi Sudhir Gupta!

    I understand :). You have 2 options in Symfony:

    1) You can manually check and deny access in every controller: https://knpuniversity.com/scre... - that's very similar to what you did in normal "PHP". Symfony already makes the User available to you on every request (it loads it from the session). Then, you can check to see if the user is logged in inside every controller.

    2) An easier way is to use access_control. In this model, you use configuration to require the user to be logged for ALL URLs. Then, you use some extra configuration to specifically allow anonymous access to *only* the pages that you want - like the login page. We show this strategy here: https://knpuniversity.com/scre...

    I hope that helps!

    Cheers!

  • 2016-06-09 Sudhir Gupta

    hi weaverryan

    I want your help with page authorization.
    In my application, i wan that all pages (Excluding Login page ) should be secured. No one can access without login. (like admin panel).
    In core PHP, what we do that, we save login credential in session and check session's data in every page.

    i don't know how i will deal with symfony.
    any help will be appreciated.. (i know you will must help me :-) )
    Thanks in Advance.

  • 2016-05-25 Sudhir Gupta

    Hi weaverryan
    Hope you are doing well.

    Actually i need one help regarding Swiftmailer. we are using own development server which is lenux.
    we have apptix mail server.
    this is the code what i am using.

    setTo(array(
    "hello@gmail.com" => "Aurelio De Rosa",
    "test@fake.com" => "Audero"
    ));

    $message->setSubject("This email is sent using Swift Mailer");
    $message->setBody("You're our best client ever.");
    $message->setFrom("account@bank.com", "Your bank");

    // Send the email
    $mailer = Swift_Mailer::newInstance($transport);
    $mailer->send($message);

    Ref-: https://goo.gl/mhl3yU
    -----------------------------
    ?>

    strange things is everything's going good.
    i am geeting "true" as a response but mail is going going out in reality.
    when i checked log file. there is no error.

    so million dollar question is where is going that mail or is mail not going in reality?
    i do lot of RnD. Also i use others codes from stackoverflow but response was same.

    Pls help me to resolve this issue.

  • 2016-03-29 weaverryan

    Yes, you're absolutely right - we get to take advantage of all that junk ;).

    A framework is a great choice for an application of any size. The real question should not be the *size* of the application, but the *type* of the application. For example, if you're building a content site, then using Wordpress or Drupal is probably better (because you can build the app faster and give your user good admin tools without any work). Or, if you're building an Ecommerce store, you might use Magento (there are also some Ecommerce products built on Symfony, if your store is a bit more complex and you want to use Symfony code). But, if you have a 10-page CRUD with a custom database, a framework is great for that - you will be able to build that much faster than if you use raw PHP.

    Cheers!

  • 2016-03-24 Sudhir Gupta

    Thanks you weaverryan
    u had briefed nicely.

    now i have clear point.
    that why Simple Wordpress also have huge files.. its really Annoyed while uploading or moving sites.
    But we have to suffer this, bcz we are getting advantage of that junks. :-).

    however if i say that, framework is not suitable choice for small websites. such as 10 page's simple CRUD website..is it wrong ( as a developer perspective )

    lastly thank you once again weaverryan to clarify my doubt.

  • 2016-03-23 weaverryan

    Hi Sudhir!

    In truth, you are probably not using many of those files. A Symfony app has many dependent packages (in composer.json). And each of these come with multiple classes: you may use some of those classes, but you may not use all of them. Those packages also ship with *their* unit tests... which you *certainly* don't need, but they're present anyways (if that were to be "fixed", it would be done in Composer itself).

    So for the most part, this is normal - it's a product of modern web development where you have a lot of tools at your disposal. If you knew that you weren't using a specific package (e.g. you're not using SwiftMailer to send emails), then you could remove that from composer.json and lessen the files.

    I know it's not ideal - but storage and bandwidth are cheap. Other languages (and all PHP frameworks) have a similar situation - Node.js (npm) is infamous for having a *huge* number of files.

    What you *can* do to save bandwidth is use a deploy mechanism that doesn't upload the files each time. For example (just thinking of very simple deploy solutions): you could clone your git repository on the server and run a "git pull". Or, you could use rsync - that only deploys *changed* files.

    I hope this helps!

  • 2016-03-23 Sudhir Gupta

    hi weaverryan
    hope you are doing well.

    i am little suspect on deployment issue.
    in my application, there are only 20 page. when i am uploading application into production server. i am amazed to see that, around 1K+ file being transfer.
    lot of unknown file with long name and different DIR.

    I don't know why?
    is this mandatory for every application.
    I don't think it is good to waste 1K files Bandwidth and space for only 20 pages' website.

    will you help me a correct approach pls ??

  • 2016-03-06 weaverryan

    Hi Sudhir!

    Yes, your friend is smart :). The problem is that - in a controller - if you have a __construct() function, you do *not* have access to the service container yet. That means you cannot use $this->get() or any of the other shortcuts like $this->render (which uses the service container to get the templating service). So, there is no problem with having __construct, as long as you understand that you cannot access the service container.

    Often, people want a __construct() method so that they can initialize some data - e.g. the path to your book.xml file. For example:

    private $bookXmlPath;

    public function __construct()
    {
    // will not work because we don't have access to the container yet - $this->get() will fail
    $this->bookXmlPath = $this->get('kernel')->getRootDir().'/../web/book.xml';
    }

    Instead, just use a private method:

    // still inside your controller
    private function getBookXmlPath()
    {
    return $this->get('kernel')->getRootDir().'/../web/book.xml';
    }

    In general, it's good to do as little work as possible in the __construct() function (of any class). By using private functions like this, you can do any work "lazily" - i.e. only perform the logic in this method *if* you actually need it. But for controllers, the big reason is not having access to the service container :). I hope that helps!

  • 2016-03-04 Sudhir Gupta
    ha ha ha.. 
    thanks weaverryan , i am author too so several time my finger get excited :-)

    file_get_contents is working file. but is it not possible with load file.
    see, in core php i parse xml file with $file=simplexml_load_file('book.xml');
    so i was just exploring that, is there same scopes with symfony or not.
    however my problem is solved now.

    I have one confusion that can i write __construct method in controller file
    one of my friend suggest me that it is not a good practise to write __construct file in defaultController or any Controller file.
    so write a another class file and the use __construct

    are u agree with that??

    Thnks
    Sudhir
  • 2016-03-03 weaverryan

    Hi Sudhir!

    Ha, I like your "but but but" :). Your code mostly looks ok. But, you're missing the file_get_contents:

    $xml = file_get_contents($this->get('kernel')->getRootDir().'/../web/book.xml');

    Also, it probably doesn't matter (I'm guessing you're on windows?) - but use the forward slash (/) instead of (\) - the / will work even on Windows. And ultimately, do a `dump($xml);die;` to make sure that it actually is loading your XML. I think it's just not being loaded from the file.

    Cheers!

  • 2016-03-01 Sudhir Gupta

    Hi team,
    I came with a issue.
    i am trying to parse a xml with Symfony 2.8
    currently i am using lalit's xml2Array
    my code is-:

          $xml =$this->get('kernel')->getRootDir().'\..\web\book.xml';
    $a=new XML2Array;
    $array = $a->createArray($xml2);

    echo '<pre>';
    print_r($array);
    echo '</pre>';

    return new Response('Its work');

    when i am using code i am getting an error called <big> " [XML2Array] Error parsing the XML string." </big>
    But but but,
    Catch is if i copied the xml and paste as a string in $xml variable ($xml=" your - xml - string -goes - here")
    then its working perfectly.

    I do lot of How's and what's but still not get any clues.
    May u help me weaverryan

    Thnks
    Sudhir Gupta Mumbai

  • 2016-02-25 Sudhir Gupta

    yes weaverryan, lastly i did the same.

    Thank for helping me.
    however enjoying alot with symfony 2.8 :-)

  • 2016-02-25 weaverryan

    Hi Sudhir!

    Yes, I know the issue :). Move this *out* of the __construct() method and into loadXmlAction(). If this is some value you want to re-use across multiple "actions" in this controller, then move this logic into a "private function getBookXmlPath()" and call it from the actions where you need it.

    The issue is that the "get()" method makes a call to Symfony's Container. But, the container is injected into your controller *after* its constructed. In other words, you don't have access to the container (or the get() function) from within __construct(). But that's ok - if you follow my advice above, you'll be able to do whatever you need.

    Cheers!

  • 2016-02-24 Sudhir Gupta

    Hi weaverryan ,
    pls look a scenario.
    i have a controller file called xmlController . there is a function ""loadXmlAction"
    in this action i wanted to load a xml file which is located in "c:\wamp\www\blog\web\book.xml"
    i am not able to load this file.
    actually i am not getting accurate url.

    what i am trying that
    $getPath = $path =$this->get('kernel')->getRootDir().'/../web/book.xml'; (someone tell that, its wrong approach. is it weaverryan??

    Now pain is when i am trying to same to in __construct() method i am geeting error.

    ----------------------------------------------------------------------------------

    Error: Call to a member function get() on a non-object

    500 Internal Server Error - FatalErrorException


    ----------------------------------------------------------------------------------
    may u help me that how can resolve this issue?
    is there any way to get web folder link inside controller?

    Tnks
    Sudhir Gupta
    Mumbai.

  • 2016-02-11 weaverryan

    Nice work and thanks for sharing :)

  • 2016-02-09 Sudhir Gupta

    Thnks Weaverryan,

    Finally I success to deploy my test project on linux shared hosting. It is so easy now but was too difficult day back. :-)
    I write step by step guideline for other Developer who are facing same issues.

    How to Deploy Symfony 2.8 or 3.0 Project on Linux Hosting Server.
    http://99crashpoint.blogspot.i...




    :-)

  • 2016-02-09 weaverryan

    Sudhir Gupta

    Yes, exactly! A symlink means that public_html is equivalent to the web folder - if you look in the public_html folder, it is the contents of the web folder.

    Really, any PHP hosting will work - the only thing that you need to make sure you get right is that the "document root" (e.g. public_html) points to the web directory. I remember originally doing this kind of stuff years ago - it was a little difficult at first, but it has paid off to learn it :).

    Cheers!

  • 2016-02-08 Sudhir Gupta

    Bdw, What is the symlinks??
    you mean that, web folder are equivalent to public_html folder in lenux hosting ??

  • 2016-02-08 Sudhir Gupta

    ahha
    its seems too painful for me.
    i use git / Svn but not too much..
    is there any easy solution similar to hosting core php files??

  • 2016-02-08 weaverryan

    Hi Sudhir!

    Yes, deploying can be a pain :). There are a *bunch* of different things that could be going wrong in your case. But let me give you some tips:

    1) It's probably not your issue, but there are better (and easier) ways to get your files to the server than FTP :). One way that I find really easy - but still effective - is to do a "git clone" of my code directly on the server and then later do a "git pull" to execute it. Also, if you hate hosting, one interesting thing to look into might be a platform as a service (PAAS) hosting where you can just "push" your code to them and they take care of everything afterwards. For this, you have Platform.sh, Heroku, Cloudways and more (the first 2 have documentation on symfony.com). Those also have a learning curve, but once it's working, you good!

    2) So as you mentioned, the fact that you have to use "/web/my-url" means that the approach isn't quite right. You need to make sure that your "web" directory is your "document root". Fortunately, even on something as simple as shared hosting, there is a nice trick to do this using symlinks. Suppose that there is a directory called "public_html" on your server that is your document root. Here's what I would do:

    rm -rf public_html

    # clone the project do a "code" directory
    # or FTP - but the point is: put it in some directory *not* named public_html
    git clone https://myproject.git code

    ln -s /path/to/this/directory/code/web public_html

    Now, public_html will actually be your project's web directory. This may be part - or all - if the issue that you're hitting.

    Good luck!

  • 2016-02-08 Sudhir Gupta

    Hi Team KNP,
    I use you article and learned symfony.
    I build an application in local system but i am unable to deploy on server. (I have Lenux and Window hosting both)

    However i try to upload symfony project folder via FTP and test via url but i failed.
    i got directory listing there.
    when i access "/web/my-url/" then i get Front end ajax is not working.
    I know this is a wrong approach but i did because of curiosity.

    May you please help me that how to run my application on lenux server?

    Tnks
    Sudhir Gupta

  • 2015-09-25 weaverryan

    Hi there!

    We'll be updating this tutorial soon, so I'd like to take your recommendations into account. In this tutorial, we actually build a real events site, step-by-step, touching on routes, controllers, entities and repositories along the way (with chapters on each topic individually). What pieces do you think are missing to make this more practical? Practical is *exactly* what we aim for, and we usually hear that people are very happy with this :).

    Cheers!

  • 2015-09-25 gintare

    Generally very good course with practical examples are by David Morales: "Introduction to web development with Symfony2", https://www.udemy.com/introduc...
    the code is in the last lecture :)

  • 2015-09-13 A Maria

    Hi,
    I must say that this is still the best intro to Symfony out there. Thanks! A couple of things...

    1. Initially, the time value caused an error in my template (until I downloaded your files). I wound up installing the Intl extension for Twig, which gave me a localizeddate filter. It was a good exercise for me :)

    2. For anyone looking to setup vhost on Windows, try using WAMP. You need to add the host name to hosts file usually located at C:\Windows\System32\\drivers\etc\hosts. You have to edit it as an administrator, Then add a vhost file for it in path/to/wamp/vhosts,

  • 2015-08-24 weaverryan

    Hey Léo!

    Thanks for the nice words! You're right that this series is from Symfony 2.4, and though most things work fine on 2.7, there are some differences and newer stuff that's not covered. We'll update these near the end of this year, around when Symfony 2.8/3.0 comes out. Pretty much everything else on the site uses 2.6 or higher :).

    Cheers!

  • 2015-08-24 Léo Li

    Hi there,
    I enrolled and watched several in Episode 1. You're the only one but also the best one I can find in the internet who offer screencasts of Symfony2 with such detail. You guys did a really great job!
    Still, I got some issues that cause by the difference between versions. I use Symfony 2.7, but the version in these videos is still 2.4 (tell me if I am wrong). Do you have a plan to update these videos ?

  • 2015-04-25 Shairyar Baig

    Finally managed to get some time to watch ep1, it was refreshing. Cant wait to watch rest of the episodes. Great job

  • 2015-04-14 weaverryan

    Hi Oscar!

    I think that's exactly what it was. It's still odd - Twig automatically rebuilds its cache when it detects that a source file has been modified. But still, in some edge cases, that cache won't rebuild for one reason or another. So yea, I think that's it - but I don't want you to think that it's normal - this shouldn't usually happen :).

    Anyways - glad it's working for you!

  • 2015-04-14 Oscar

    Hi again, last night I tried again and did not change anything but it was working. I am wondering if it was a caching issue, if it was using and old cached file?

  • 2015-04-13 Oscar

    Hi weaverryan,

    Thanks for the quick response. It is really strange, I copied "edit.html.twig, new.., index.. and show.." twig files from resources/event folder into "src/Yoda/EventBundle/Resources/views/event" folder and created a "layout.html.twig" file in "src/Yoda/EventBundle/Resources/views/".

    My layout file looks like this:

    {# src/Yoda/EventBundle/Resources/views/layout.html.twig #}
    {% extends '::base.html.twig' %}

    {% block title 'Events' %}

    The problem is when I visit this route:

    http://sandbox.dev:8080/starwa...

    I see that my page title is still Welcome! not Events. So layout file is not kicking in for the index page. But this is really strange. When I remove the layout.html.twig from the views directory and visit "http://sandbox.dev:8080/starwa..." I get this error:

    Unable to find template "EventBundle::layout.html.twig" in EventBundle:Event:show.html.twig at line 1.

    500 Internal Server Error - InvalidArgumentException

    3 linked Exceptions:

    Twig_Error_Loader »

    InvalidArgumentException »

    InvalidArgumentException »

    So when I put it back and visit the rout I see that map and the event. But index page doesn't use the layout.html.twig. It is still using the ::base.html.twig. Maybe I missed something. The indexAction in the event controller looks like this:

    public function indexAction()
    {
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('EventBundle:Event')->findAll();

    return $this->render('EventBundle:Event:index.html.twig', array(
    'entities' => $entities,
    ));
    }

    So it is using the index.html.twig which extends layout.html.twig which extends base.html.twig. And this is the begining of index.html.twig:

    {% extends 'EventBundle::layout.html.twig' %}

    {% block body %}

    <section class="events">
    .....

    I appreciate your help. Thanks for looking at this.

    Regards

    Oscar

  • 2015-04-12 weaverryan

    Hi Oscar!

    When we click to go back to "/event/", we *are* going back to the index page, just like you're describing :). BUT, this index page *does* show the map. These pages are missing their styling (we'll fix that in a second), but both /event/ and /event/1/show should have a map on it AND you're right that /event/ is an index page.

    If you're missing it, no worries. You may have just not copied in all of my "example" code for these templates: https://knpuniversity.com/scre.... Make sure you've done this, and you should see the map on the index page too (I just double-checked this, it works!).

    Let me know how it goes!

  • 2015-04-12 Oscar

    I am watching the videos and followed the instructions. But there is a problem. Around min 54:38 instructor clicks on edit and ../app_dev.php/event/1/edit shows that you can edit the event but then loads some new css. But when goes back to "../event/" rout, an event with a map is shown. When I visit the same rout I see an index page. I fpnz see a page with a map. The page with the map only shows when I click on show or edot. So in fact the page you are showing in the video at min. 56:42 should have a route like this ../event/1/show not ../event/. What am I doing wrong?

  • 2015-02-07 weaverryan

    Hey Nick!

    This kind of thing isn't supported, so you'll have to handle it manually (i.e. query for one object, read the "fk" column, use it to query the other db), which has the advantage of at least being very understandable. You can also get fancy if you want - like this: http://stackoverflow.com/quest.... This approach can even be used to "join" between a relational db and a nosql db. But measure whether it's worth your trouble first :).

    Cheers!

  • 2015-02-06 Nick

    Hello,

    What is the best practice to add an one to one cross database relationship with Doctrine?
    Seems by default doctrine doesn't support this and wonder if we can achieve this somehow.

    Thanks a lot.

  • 2014-12-04 Joshua Andrew Jourdain

    no, it helps. i like the idea of web/assets/vendor... i appreciate you taking the time to answer.

  • 2014-12-04 weaverryan

    Hey Joshua!

    There is no best practice, and that's partially on purpose (though I think we should recommend something just in case, in the future). Basically, my stance is that Symfony has nothing to do with your web assets, especially if you're using something like gulp (which is awesome that you are). So, the best best practice would be to follow what the frontend world is doing. But, I will tell you that I typically like having a web/assets directory where everything lives (e.g. something like web/assets/css, web/assets/js, and even web/assets/vendor for bower - but this is totally a "me" thing).

    For "dev" things (like sass files), I've had success putting them into an assets directory at the root of my project. Then gulp/grunt tasks process and move them into web/assets (or whatever your path is).

    Does that help - or is my answer too generic? :D

    Cheers!

  • 2014-12-04 Joshua Andrew Jourdain

    can't go into detail here, but basically set it up by using gulpfile at root level; browsersync for twig sass and javascript; i have my bower assets saved in the "web" directory in a sub-directory called "components"; any best practices regarding front-end assets and where they should live in production vs. dev environments?

  • 2014-11-17 Joshua Andrew Jourdain

    I am planning on trying php storm; will let you know what setup i land on, as this week i have some time carved out to toy around with some development workflows.

  • 2014-11-17 weaverryan

    Hey Joshua!

    Awesome that you're using yeoman and Gulp - I think those are great tools and want to put up a new screencast about those here soon to spread the love!

    About the live-reload, I don't have much experience here. But the problem should be somewhat simple. If you're using livereload already with Gulp, can it be used just to refresh whatever page the browser is on? About livereloading with Twig, the source to check out is definitely PHPStorm: http://blog.jetbrains.com/phps.... I can't vouch for it personally, but if you've tried it (or will try it), I'd love it if you commented on your experiences here.

    Cheers!

  • 2014-11-14 Joshua Andrew Jourdain

    watched this episode; great stuff. an important question though: i am used to yeoman and gulp for front-end task automation; i typically use a gulpfile to compile sass, lint js, AND watch and livereload html pages in the browser in development. what is the best way to do livereload with symfony? is there a "best practice" for integrating livereload in symfony development for twig and gulp tasks for assets?(fat chance as the speed of these tools' evolution is breakneck and because of the chasm that apparently exists between frontend workflow resources and backend workflow resources)

  • 2014-10-17 Nick

    Hehe nice I do something very similar with Propel and

    glorpen/GlorpenPropelBundle which add Listener Events in Propel.

    So we have the same approach! Thanks a lot.

  • 2014-10-17 weaverryan

    Hi Nick!

    Wow, another great question :). Actually, what you should do there is create a Doctrine event listener (http://knpuniversity.com/scree.... Since this listener is a service, it will be able to do all the moving you need. This is actually the "correct" (for lack of better word) way to do this.

    Now, how do you know that the image's category has changed from inside the listener? You have 2 choices:

    1) When you listen to preUpdate, Doctrine passes you a `PreUpdateEventArgs` object (http://doctrine-orm.readthedoc.... This has a `hasChangedField` method on it, which you *should* (disclaimer: I haven't tried this on relationship fields) be able to use to see of the category has changed. You *should* also be able to use getOldValue to get the original Category.

    2) Only if the above does *not* work, you'll need to create a non-persisted property like `originalCategory` and set this from inside setCategory(). Then, if this property is not null, you'd move things around from inside your listener.

    If this sounds a bit crazy, believe me, it's worth it. I'm all about making things simple, but this type of philosophy will mean that you have several small/medium classes doing different jobs, instead of one gigantic Image entity doing everything.

    Cheers!

  • 2014-10-17 Nick

    And what if you want to move an image when change its category? (image has category and image folder is category name, so when you want to move image to another category need to physically move it to another folder)

    This wont be possible on post save as long as I cant call services from Entity/Models.

  • 2014-10-17 weaverryan

    Hey Nick!

    Great question! And this is tricky. The short answer is that you can't (and should not) get the container in an entity. Instead, create a separate service (e.g. PathManager) that is able to give you what you want. So:


    $image = // ... query for some Image entity object


    // don't try to do this, because that function would need the container
    $path = $image->getFilenameWithPrefix()


    // instead, grab a service that has your parameter injected into it
    $path = $this->container->get('my_path_manager_service')->getImagePath($image);

    This is lacking some details, but there's a big philosophical difference that I hope you see! If not, let me know!

    Cheers!

  • 2014-10-09 Nick

    Guys can you please create a video about which is the best practice to get container in a Model or Entity? Imagine you want to load an image and have filename in database in an object Image
    So to get Path you need

    $container->getParameter("assets_prefix").$image->getFilename()

    But inside model you cant $container->getParameter("assets_prefix")

  • 2014-10-01 weaverryan

    Hey again!

    Oooh, updates! You *can* now download the completed code for most tutorials. Just download the code and you should see a "finished" directory.

    Cheers!

  • 2014-09-19 JREAM

    This is a brilliant series, I am enjoying it to compliment the Symfony Book. This is really the PHP version of Django in my mind.

  • 2014-08-16 Edison Valdez

    Hey Lucas,I had the same problem...if you guys someday found out how to setup vhost for windows 8, just let please everybody know...I will do the same for sure.
    Meanwhile let's go to the second screencast! Love the frst one, good job!

  • 2014-08-10 weaverryan

    Hey!

    Cool, so you're very close. You just need to download Composer and then run "php composer.phar install". The files you download are the project, but don't contain all the external library files that you need. But, Composer installs those for you. In case you're new to Composer, we have a screencast for it as well: http://knpuniversity.com/scree...

    Let me know if that helps!

  • 2014-08-10 weaverryan

    Hey Lucas!

    Sorry you had trouble getting Vhosts setup in Windows! It's tricky because, while Apache is always the same, *where* Apache lives is very different on different systems (so where the files are you need to edit are different). As an alternative while developing, I'd highly recommend using the built-in PHP web server, which you can start by going into a command line and running "php app/console server:run".

    Good luck!

  • 2014-08-09 kshitiz

    I download the files to my root; http://localhost:8888/knp1/web/

    And getting these errors: plz help::

    Warning: require_once(/Applications/MAMP/htdocs/knp1/web/../app/bootstrap.php.cache): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/knp1/web/app.php on line 6

    Fatal error: require_once(): Failed opening required '/Applications/MAMP/htdocs/knp1/web/../app/bootstrap.php.cache' (include_path='.:/Applications/MAMP/bin/php/php5.5.10/lib/php') in/Applications/MAMP/htdocs/knp1/web/app.php on line 6

  • 2014-08-08 weaverryan

    We'll make this easier soon, but for now, you can go download the starting code for episode 2 (it will match the finished code for episode 1). If you own the video, just click the "Download" button on the top right. If you don't, you can grab it (at least for right now) off of GitHub on the episode2-start branch: https://github.com/knpuniversi...

    Cheers!

  • 2014-08-08 kshitiz

    hi, can you please tell me from where can i download the complete working project which is just finished at the end of the course?

  • 2014-08-04 weaverryan

    Hey!

    I might be able to do that :). Can you link to which part you're talking about? Is it on this chapter? http://knpuniversity.com/scree...

    Thanks!

  • 2014-08-01 mikiplus

    About the twigs of the Event. A pair of screenshots of the "should be like that" page, could be useful. Thanks!

  • 2014-07-14 weaverryan

    Haha, I agree - I always like to say "Yes" to, especially when learning something new (no is actually the default, but it's subtle). The tricky thing is that Symfony 3 isn't anywhere near from being released (years away), so it's a silly question to ask. In fact, I've just proposed to have this question removed entirely - we'll see!

    Good luck and cheers!

  • 2014-07-14 SPIRITED

    My attitude most times when using installers(in general) is to follow the defaults when confused, My thought process was also that "It could potentially make me get familiar with Symfony3 even though it is not out yet". Thanks for clarifying this . .

  • 2014-07-14 weaverryan

    Hi there!

    Actually, that's not true! During Symony's installation, it asks you if you want to use the Symfony 3 directory structure. Choose NO! We're working in the core to make it much more obvious that no one should choose yes to this question (it was a bad idea to ask it at all, in my opinion).

    So, if you find yourself with the "console" in the "bin" directory and other directory structure changes that don't match up with the screencast, delete your directory, restart the install (run create-project again), and choose NO to the Symfony directory structure :).

    We'll be updating the video shortly so that you can actually see this question.

    Thanks Bourne for the comment - I don't want people (reading this or in the entire Symfony community) to be confused by this question!

    Thanks!

  • 2014-07-14 SPIRITED

    The installer asked if i wanted Symfony 3 directory structure, I chose Yes, as I usually go for the default when confused, Now Console ended up in the bin directory as it used to be in the app Directory.

    For less confusion, it is better to Answer No just to be in Sync with Screencast. . ***Edited***

  • 2014-07-04 test

    test

  • 2014-06-22 weaverryan

    Thanks for the comment! I'll add a note about this, it's an unfortunate new little thing that can be confusing. I think (hope) we'll change it in core so that it's much less confusing!

    Cheers!

  • 2014-06-22 goldfox
  • 2014-06-20 goldfox

    Nowadays when you use

    php composer.phar create-project symfony/framework-standard-edition starwarsevent @stable

    there is a dialog box asking 'Would you like to use Symfony 3 directory structure? [y/N]'. You MUST answer this with NO, 'n', to get app/console and the related console commands. As a newbie, I was stuck on this for awhile.

  • 2014-06-19 weaverryan

    Ah thank you very much! Cheers! :)

  • 2014-06-19 Faiawuks

    I really loved this screencast. I've learned more than from any other tutorial. Thanks!

  • 2014-06-07 weaverryan

    Haha, that's probably true. In an hour+ tutorial, it's hard to avoid. We'll try to expand our vocab a bit... seriously ;).

    Cheers!

  • 2014-06-07 weaverryan

    Hey there!

    $12 for all of episode 1 (all of the chapters). :).

    Cheers!

  • 2014-06-07 Vladimir

    You use the word "seriously" too much! Seriously!

  • 2014-06-04 Bubbles

    is each chapter $12 or the entire course?

  • 2014-05-15 weaverryan

    Hi there!

    If you buy all 4 episodes, it's $38, so there is a discount :). You don't need to buy them all at once either - you can buy them one at a time and you'll get the discount once you have the last episode in your cart.

    I really recommend getting the first episode and seeing if it works for you :).

    Cheers!

  • 2014-05-15 SPIRITED

    Is there any discount to buying the entire series, it seems expensive for $12 an episode, but it might just worth it if an average person can learn for real.

  • 2014-04-28 weaverryan

    My god, embarrassing! Thanks for the tip - I've fixed this (https://github.com/knpuniversi... and gotten it deployed right away!

    Cheers!

  • 2014-04-24 mikiplus

    for god sake, it's "Chewbacca"!

  • 2014-04-21 weaverryan

    Hi spellbinder!

    You're code looks ok to me (of course, use a normal apostrophe instead of the fancy ‘’, but I'm sure the comments just changed that for you). Make sure you *don't* have an

    {% endblock %}
    in this case.

    And let us know what the error is and we'll see if we can help :).

    Cheers!

  • 2014-04-21 weaverryan

    I'm glad you like the updated one - thanks! We don't have any concrete dates for the next episodes - but my hope would be episode2 in May :).

    Cheers!

  • 2014-04-17 spellbinder

    {% block title ‘Some Twiggy Goodness’ %} failed in my test

  • 2014-04-13 Enkhbilguun E.

    Hi Ryan,

    Updated tutorial is awesome. Even greater than the previous. Do you have any expectation/plan on releasing updates for the next episodes?

    Thanks

  • 2014-04-09 weaverryan

    Hi Hans!

    Actually, episode 1 has already been updated to Symfony 2.4, so it's completely ready to go :). We'll be updating the other episodes over the next couple of months, but you shouldn't run into any huge issues. And if you buy the 2.2 version, you'll get the upgraded version automatically for free when it comes out (and we'll email you).

    Hope that helps!

  • 2014-04-09 Hans Nieuwenhuis

    Hi,
    I am using 2.4, will this give problems, since the most screencasts are for symphony 2.2
    Regards

  • 2014-04-07 weaverryan

    You're right! Thanks, I missed that - I've updated the code download again with this change.

    Thanks and cheers!

  • 2014-04-07 Guest

    Thanks Ryan. Verified the updated edit twig file and edit works fine. However, delete still doesn't work. Changing it from {{ form_widget(delete_form) }} to {{ form(delete_form) }} does the trick.

  • 2014-04-07 weaverryan

    All fixed now! There was indeed a mistake in the template code - you can see more details here: http://knpuniversity.com/scree... - but everything should be all good now :).

    Thanks!

  • 2014-04-07 weaverryan

    Hi guys!

    Thanks for your comments here! Yes, there were in fact 2 issues:

    1) On http://knpuniversity.com/scree..., the written path in the code block was wrong (it's correct in the video). Instead of adding the <link> tags to layout.html.twig in the bundle, we actually add them to base.html.twig (in app/). That avoids the "bundles" config.yml problem (which I mention in episode 4). I've fixed this here (https://github.com/knpuniversi... thanks to you guys :).

    2) The template code in the download *was* indeed out of date - thanks for pointing that out. I've updated it, so if you download the code now, you'll get the updated templates. That fix is here: https://github.com/knpuniversi...

    Thanks for the reports - all should be well now! If you ever think anything else might be amiss or if I can help out in any way, just let me know!

    Cheers!

  • 2014-04-06 Guest

    As a workaround as Dan mentioned, I changed {{ form_widget(edit_form) }} and {{ form_widget(delete_form) }} in the edit.html.twig file to {{ form(edit_form) }}, {{ form(delete_form) }} and used the first set of update/delete buttons (not the save/delete ones) and the edit/delete functionality works.

  • 2014-04-06 Guest

    Just saw your posts, I'm getting the same results.

  • 2014-04-06 Guest

    I've purchased the first episode and noticed that when using the twig files the update/delete code no longer works. To double-check I remade the CRUD controller which worked fine with the default twig, as soon as I switched over I noticed the update/delete code was broken. Is this just me?

    What I am seeing with the custom edit twig are 2 sets of buttons for update/delete and one set is save/delete. When I attempt to update and select either one of the update or save buttons the text change is reverted back to the original text while remaining on the edit page. And selecting delete just brings me back to the main page without deleting anything.

  • 2014-04-02 Daniel Harper

    The extra twig files that are part of the download for crud operations don't seem to work for me, delete/updating records just does nothing not even any errors.

    I had to dump this {{ form(edit_form) }} into the twig file and then it looked awful but I could update and delete

    Also you need to add a line about assetic and adding EventBundle into the square brackets, don't think that was mentioned anywhere.

    Symfony 2.4

    Cheers Dan

  • 2014-04-01 weaverryan

    Absolutely not :) - if you buy the 2.2 version, you'll get the 2.4 version for free when it comes out. We'll even email you to let you know it's ready.

    Cheers!

  • 2014-04-01 weaverryan

    Hi Hans!

    You can watch it as often as you want and it's yours forever :). You can watch it here on the site, or download the full video locally and watch it from your computer whenever you want.

    We don't have an option to buy fully access to all the screencasts for a period of time right now, but it's something we're thinking about offering very soon. Would you be interested in something like that?

    Cheers and thanks!

  • 2014-04-01 hans nieuwenhuis

    Hi, if i buy a screencast, how long or how often can i watch it?
    Is there an option to buy full access for a year ?
    Regards,
    Hans