Symfony2 Jobeet Day 16: The Mailer

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.
Yesterday, we added a read-only web service to Jobeet. Affiliates can now create an account but it needs to be activated by the administrator before it can be used. In order for the affiliate to get its token, we still need to implement the email notification. That’s what we will start doing in the coming lines.

The symfony framework comes bundled with one of the best PHP emailing solution: Swift Mailer. Of course, the library is fully integrated with symfony, with some cool features added on top of its default features. Let’s start by sending a simple email to notify the affiliate when his account has been activated and to give him the affiliate token. But first, you need to configure your environment:
[crayon-5ba2108f56b31048468411/]

For the code to work properly, you should change the address@example.com email address to a real one, along with your real password.

Do the same thing in your app/config/parameters_test.yml file.

After modifying the two files, clear the cache for both test and development environment:
[crayon-5ba2108f56b3f227571374/]
Because we set the mailer transport to gmail, when you will replace the email address from “mailer_user”, you will put a google email address.

You can think of creating a Message as being similar to the steps you perform when you click the compose button in your mail client. You give it a subject, specify some recipients and write your message.

To create the message, you will:

  • call the newInstance() methond of Swift_message (refer to the Swift Mailer official documentation to learn more about this object).
  • set your sender address (From:) with setFrom() method.
  • set a subject line with setSubject() method.
  • set recipients with one of these methods: setTo(), setCc() or setBcc().
  • set a body with setBody().

Replace the activate action with the following code:
[crayon-5ba2108f56b46268872061/]
Sending the message is then as simple as calling the send() method on the mailer instance and passing the message as an argument.

For the message body, we created a new file, called email.txt.twig, that contains exactly what we want to inform the affiliate about.
[crayon-5ba2108f56b4c136274347/]
Now, let’s add the mailing functionality to the batchActionActivate too, so that even if we select multiple affiliate accounts to activate, they will receive their account activation email :
[crayon-5ba2108f56b52653095784/]

The Tests

Now that we have seen how to send an email with the symfony mailer, let’s write some functional tests to ensure we did the right thing.

To test this new functionality, we need to be logged in. To log in, we will need an username and a password. That’s why we will start by creating a new fixture file, where we add the user admin:
[crayon-5ba2108f56b59867722317/]
In the tests, we will use the swiftmailer collector on the profiler to get information about the messages send on the previous requests. Now, let’s add some tests to check if the email is sent properly:
[crayon-5ba2108f56b5f447146937/]
If you run the test now, you’ll get and error. To prevent this for happening, go to your config_test.yml file and make sure that the profiler is enabled in the test environment. If it’s set to false, change it to true:
[crayon-5ba2108f56b68749126827/]
Now, clear the cache, run the test command in your console and enjoy the green bar :
[crayon-5ba2108f56b6e675881173/]
Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Symfony2 Jobeet Day 15: Web Services

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.
With the addition of feeds on Jobeet, job seekers can now be informed of new jobs in real-time.

On the other side of the fence, when you post a job, you will want to have the greatest exposure possible. If your job is syndicated on a lot of small websites, you will have a better chance to find the right person. That’s the power of the long tail. Affiliates will be able to publish the latest posted jobs on their websites thanks to the web services we will develop today.

Affiliates

As we already said in day 2 of this tutorial, an affiliate retrieves the current active job list.

The fixtures

Let’s create a new fixture file for the affiliates:
[crayon-5ba2108f5992e703760899/]
Now, to persist the data defined in your fixture file, just run the following command:
[crayon-5ba2108f5993b475569059/]
In the fixture file, the tokens are hardcoded to simplify the testing, but when an actual user applies for an account, the token will need to be generated Let’s create a function to do that in our Affiliate class. Start by adding the setTokenValue method to lifecycleCallbacks section, inside your ORM file:
[crayon-5ba2108f5996e498768152/]
Now, the setTokenValue method will be generated inside the entity file when you will run the following command:
[crayon-5ba2108f59978197269232/]
Let’s modify the method now:
[crayon-5ba2108f5997d614150110/]
Reload the data:
[crayon-5ba2108f59983182716028/]

The Job Web Service

As always, when you create a new resource, it’s a good habbit to define the route first:
[crayon-5ba2108f59988741151172/]
As usually, after you modify a routing file, you need to clear the cache:
[crayon-5ba2108f5998d593739913/]
The next step is to create the api action and the templates, that will share the same action. Let us now create a new controller file, called ApiController:
[crayon-5ba2108f59993170084888/]
To retrieve the affiliate using his token, we will create the getForToken() method. This method also verifies if the affiliate account is activated, so there is no need for us to check this one more time. Until now, we haven’t used the AffiliateRepository yet, so it doesn’t exist. To create it, modify the ORM file as following, then run the command you used before to generate the entities.
[crayon-5ba2108f5999a194096239/]
Once created, it is ready to be used:
[crayon-5ba2108f5999f348093868/]
After identifying the affiliate by his token, we will use the getActiveJobs() method to give the affiliate the jobs he required, belonging to the selected categories. If you open your JobRepository file now, you will see that the getActiveJobs() method doesn’t share any connection with the affiliates. Because we want to reuse that method, we need to make some modifications inside of it:
[crayon-5ba2108f599a5258244843/]
As you can see, we populate the jobs array using a function called asArray(). Let’s define it:
[crayon-5ba2108f599ab752082710/]

The xml Format

Supporting the xml format is as simple as creating a template:
[crayon-5ba2108f599b0558318167/]

The json Format

Support the JSON format is similar:
[crayon-5ba2108f599b6958984348/]

The yaml Format

[crayon-5ba2108f599bb156755715/]
If you try to call the web service with a non-valid token, you will receive a 404 page as a response, for all the formats. To see what you accomplished until now, access the following links: http://jobeet.local/app_dev.php/api/sensio-labs/jobs.xml or http://jobeet.local/app_dev.php/api/symfony/jobs.xml. Change the extension in the URL, depending on which format you prefer.

Web Service Tests

[crayon-5ba2108f599c1548133222/]
Inside the ApiControllerTest file, we test that the request formats are correctly received and the pages requested are correctly returned.

The Affiliate Application Form

Now that the web service is ready to be used, let’s create the account creation form for affiliates. For that, you need to write the HTML form, implement validation rules for each field, process the values to store them in a database, display error messages and repopulate fields in case of errors.

First, create a new controller file, named AffiliateController:
[crayon-5ba2108f599ca834560792/]
Then, change the Affiliates link in the layout:
[crayon-5ba2108f599d0304648327/]
Now, we need to create an action to match the route from the link you just modified it earlier:
[crayon-5ba2108f599d5531059652/]
We have the name of the route, we have the action, but we do not have the route. so let’s create it:
[crayon-5ba2108f599da778490039/]
Also, add this to your routing file:
[crayon-5ba2108f599df798151252/]
The form file also needs to be created. But, even if the Affiliate has more fields, we won’t display them all, because some of them must not be editable by the end user. Create your Affiliate form:
[crayon-5ba2108f599e5193249298/]
Now, we need to decide whether or not the Affiliate object is valid after the form has applied the submitted data to it. To do this, add the following code to your validation file:
[crayon-5ba2108f599ea266084885/]
In the validation schema, we used a new validator, called UniqueEntity. It validates that a particular field (or fields) in a Doctrine entity is (are) unique. This is commonly used, for example, to prevent a new user to register using an email address that already exists in the system.

Don’t forget to clear your cache after applying the validation constraints!

Finally, let’s create the view for the form too:
[crayon-5ba2108f599f0758812006/]
When the user submits a form, the form data must be persisted into database, if valid. Add the new create action to your Affiliate controller:
[crayon-5ba2108f599f7626328574/]
When submitting, the create action is performed, so we need to define the route:
[crayon-5ba2108f599fd814670646/]
After the affiliate registers, he is redirected to a waiting page. Let’s define that action and create the view too:
[crayon-5ba2108f59a02980695475/]
[crayon-5ba2108f59a08798185246/]
Now, the route:
[crayon-5ba2108f59a0d246530045/]
After defining to routes, in order to work, you need to clear the cache.

Now, if you click on the Affiliates link on the homepage, you will be directed to the affiliate form page.

Tests

The last step is to write some functional tests for the new feature.
[crayon-5ba2108f59a12220328143/]

The Affiliate Backend

For the backend, we will work with SonataAdminBundle. As we said before, after an affiliate registers, he needs to wait for the admin to activate his account. So, when the admin will access the affiliates page, he will see only the inactivated accounts, to help him be more productive.

First of all, you need to declare the new affiliate service inside your services.yml file:
[crayon-5ba2108f59a1d379807971/]
After that, create the Admin file:
[crayon-5ba2108f59a23217146754/]
To help the administrator, we want to display only the inactivated accounts. This can be made by setting the ‘is_active’ filter to false:
[crayon-5ba2108f59a29805929049/]
Now, create the AffiliateAdmin controller file:
[crayon-5ba2108f59a2e479890377/]
Let’s create the activate and deactivate batch actions:
[crayon-5ba2108f59a33827190736/]
For the new batch actions to be functional, we have to add them in the getBatchActions from the Admin class:
[crayon-5ba2108f59a3b962685304/]
For this to work, you need to add the two methods, activate and deactivate, in the entity file:
[crayon-5ba2108f59a41906984205/]
Let’s now create two individual actions, activate and deactivate, for each item. Firstly, we will create routes for them. That’s why, in your Admin class, you will extend the configureRoutes function:
[crayon-5ba2108f59a46119345192/]
It’s time to implement the actions in the AdminController:
[crayon-5ba2108f59a4c185102444/]
Now, create the templates for the new added action buttons:
[crayon-5ba2108f59a52970928691/]
[crayon-5ba2108f59a57025585674/]
Inside your Admin file, add the new actions and buttons to the configureListFields function, so that they would appear on the page, to each account individually:
[crayon-5ba2108f59a5d428640633/]
Now, clear your cache and try it on!

That’s all for today! Tomorrow, we will take care of the emails the affiliates will receive when their accounts have been activated.
Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Symfony2 Jobeet Day 14: Feeds

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.
If you are looking for a job, you will probably want to be informed as soon as a new job is posted. Because it is not very convenient to check the website every other hour, we will add several job feeds here to keep our Jobeet users up-to-date.

Template Formats

Templates are a generic way to render content in any format. And while in most cases you’ll use templates to render HTML content, a template can just as easily generate JavaScript, CSS, XML or any other format.

For example, the same “resource” is often rendered in several different formats. To render an article index page in XML, simply include the format in the template name:

  • XML template name: AcmeArticleBundle:Article:index.xml.twig
  • XML template filename: index.xml.twig

In reality, this is nothing more than a naming convention and the template isn’t actually rendered differently based on its format.

In many cases, you may want to allow a single controller to render multiple different formats based on the “request format”. For that reason, a common pattern is to do the following:
[crayon-5ba2108f5d723183198566/]
The getRequestFormat on the Request object defaults to html, but can return any other format based on the format requested by the user. The request format is most often managed by the routing, where a route can be configured so that /contact sets the request format to html while /contact.xml sets the format to xml.

To create links that include the format parameter, include a _format key in the parameter hash:
[crayon-5ba2108f5d72e707397249/]

Feeds

LATEST JOBS FEED

Supporting different formats is as easy as creating different templates. To create an Atom feed for the latest jobs, create an index.atom.twig template:
[crayon-5ba2108f5d734605396623/]
In the Jobeet footer, update the link to the feed:
[crayon-5ba2108f5d73a820208206/]
Add a <link> tag in the head section of the layout to allow automatic discover by the browser of our feed:
[crayon-5ba2108f5d73f445166790/]
In the JobController change the indexAction to render the template according to the _format:
[crayon-5ba2108f5d759158877055/]
Replace the Atom template header with the following code:
[crayon-5ba2108f5d75f414565251/]
From the JobController (index action) we have to send the lastUpdated and feedId to the template:
[crayon-5ba2108f5d764128630184/]
To get the date of the latest post, we have to create the getLatestPost() method in the JobRepository:
[crayon-5ba2108f5d76a822745194/]
The feed entries can be generated with the following code:
[crayon-5ba2108f5d76f707231839/]
LATEST JOBS IN A CATEGORY FEED

One of the goals of Jobeet is to help people find more targeted jobs. So, we need to provide a feed for each category.

First, let’s update the links to category feeds in the templates:
[crayon-5ba2108f5d776024241922/]
[crayon-5ba2108f5d77b395391718/]
Update the CategoryController showAction to render the corresponding template:
[crayon-5ba2108f5d780304647921/]

Eventually, create the show.atom.twig template:

[crayon-5ba2108f5d787190338183/]

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Symfony2 Jobeet Day 13: Security

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.

Securing the Application

Security is a two-step process whose goal is to prevent a user from accessing a resource that he/she should not have access to. In the first step of the process, the authentication, the security system identifies who the user is by requiring the user to submit some sort of identification. Once the system knows who you are, the next step, called the authorization, is to determine if you should have access to a given resource (it checks to see if you have privileges to perform a certain action).

The security component can be configured via your application configuration using the security.yml file from the app/config folder. To secure our application change your security.yml file:
[crayon-5ba2108f5e81c840911545/]
This configuration will secure the /admin section of the website (all urls that start with /admin) and will allow only users with ROLE_ADMIN to access it (see the access_control section). In this example the admin user is defined in the configuration file (the providers section) and the password is not encoded (encoders).

For authenticating users, a traditional login form will be used, but we need to implement it. First, create two routes: one that will display the login form (i.e. /login) and one that will handle the login form submission (i.e. /login_check):
[crayon-5ba2108f5e827476072255/]
 

We will not need to implement a controller for the /login_check URL as the firewall will automatically catch and process any form submitted to this URL. But you need to create a route so that it can be used to generate the form submission URL in the login template below.

Next, let’s create the action that will display the login form:
[crayon-5ba2108f5e82d060335499/]
When the user submits the form, the security system automatically handles the form submission for you. If the user had submitted an invalid username or password, this action reads the form submission error from the security system so that it can be displayed back to the user. Your only job is to display the login form and any login errors that may have occurred, but the security system itself takes care of checking the submitted username and password and authenticating the user.

Finally, let’s create the corresponding template:
[crayon-5ba2108f5e834207523811/]
Now, if you try to access http://jobeet.local/app_dev.php/admin/dashboard url, the login form will show and you will have to enter the username and password defined in security.yml (admin/adminpass) to get to the admin section of Jobeet.

User Providers

During authentication, the user submits a set of credentials (usually a username and password). The job of the authentication system is to match those credentials against some pool of users. So where does this list of users come from?

In Symfony2, users can come from anywhere – a configuration file, a database table, a web service, or anything else you can dream up. Anything that provides one or more users to the authentication system is known as a “user provider”. Symfony2 comes standard with the two most common user providers: one that loads users from a configuration file and one that loads users from a database table.

Above, we used the first case: specifying users in a configuration file.
[crayon-5ba2108f5e83b991445226/]
But you will usually want the users to be stored in a database table. To do this we will add a new user table to our jobeet database. First let’s create the orm for this new table:
[crayon-5ba2108f5e840684612337/]
Now run the doctrine:generate:entities command to create the new User entity class:
[crayon-5ba2108f5e845287723021/]
And update the database:
[crayon-5ba2108f5e84a131754240/]
The only requirement for your new user class is that it implements the UserInterface interface. This means that your concept of a “user” can be anything, as long as it implements this interface. Open the User.php file and edit it as follows:
[crayon-5ba2108f5e850549372463/]
To the generated entity we added the methods required by the UserInterface class: getRoles, getSalt, eraseCredentials and equals.

Next, configure an entity user provider, and point it to your User class:
[crayon-5ba2108f5e856512358413/]
We also changed the encoder for our new User class to use the sha512 algorithm to encrypt passwords.

Now everything is set up but we need to create our first user. To do this we will create a new symfony command:
[crayon-5ba2108f5e85b474023552/]
To add your first user run:
[crayon-5ba2108f5e861702370908/]
This will create the admin user with the password admin. You can use it to login to the admin section.

Logout

Logging out is handled automatically by the firewall. All you have to do is to activate the logout config parameter:
[crayon-5ba2108f5e867337902625/]
You will not need to implement a controller for the /logout URL as the firewall takes care of everything. Let’s create a route so that you can use it to generate the URL:
[crayon-5ba2108f5e86c109359910/]
Once this is configured, sending a user to /logout (or whatever you configure the path to be), will un-authenticate the current user. The user will then be sent to the homepage (the value defined by the target parameter).

All left to do is to add the logout link to our admin section. To do this we will override the user_block.html.twig from SonataAdminBundle. Create the user_block.html.twig file in app/Resources/SonataAdminBundle/views/Core folder:
[crayon-5ba2108f5e871597675380/]
Now, if you try to enter the admin section (clear the cache first), you will be asked for an username and password and then, the logout link will be shown in the top-right corner.

The User Session

Symfony2 provides a nice session object that you can use to store information about the user between requests. By default, Symfony2 stores the attributes in a cookie by using the native PHP sessions.

You can store and retrieve information from the session easily from the controller:
[crayon-5ba2108f5e877489382366/]
Unfortunately, the Jobeet user stories have no requirement that includes storing something in the user session. So let’s add a new requirement: to ease job browsing, the last three jobs viewed by the user should be displayed in the menu with links to come back to the job page later on.

When a user access a job page, the displayed job object needs to be added in the user history and stored in the session:
[crayon-5ba2108f5e87c679265750/]
In the layout, add the following code before the #content div:
[crayon-5ba2108f5e882333588267/]

Flash Messages

Flash messages are small messages you can store on the user’s session for exactly one additional request. This is useful when processing a form: you want to redirect and have a special message shown on the next request. We already used flash messages in our project when we publish a job:
[crayon-5ba2108f5e888452600051/]
The first argument of the getFlashBag()->add() function is the identifier of the flash and the second one is the message to display. You can define whatever flashes you want, but notice and error are two of the more common ones.

To show the flash messages to the user you have to include them in the template. We did this in the layout.html.twig template:
[crayon-5ba2108f5e88d885242642/]
Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Symfony2 Jobeet Day 12: Sonata Admin Bundle

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.
With the addition we made in Day 11 on Jobeet, the application is now fully usable by job seekers and job posters. It’s time to talk a bit about the admin section of our application. Today, thanks to the Sonata Admin Bundle, we will develop a complete admin interface for Jobeet in less than an hour.

 

Installation of the Sonata Admin Bundle

Start by downloading SonataAdminBundle and its dependencies to the vendor directory:
[crayon-5ba2108f600b1607800679/]
To install the latest version of the SonataAdminBundle and its dependencies, give * as input.
[crayon-5ba2108f600bb652969364/]
We will also need to install the SonataDoctrineORMADminBundle:
[crayon-5ba2108f600c1185761339/]
Now, we need to declare these new bundles and dependencies, so go to your AppKernel.php file and add the following code:
[crayon-5ba2108f600c7947134705/]
You will need to alter your config file as well. Add the following at the end:
[crayon-5ba2108f600cc652309200/]
Also, look for the translator key and uncomment if it is commented:
[crayon-5ba2108f600d2674610127/]
For your application to work, you need to import the admin routes into the application’s routing file:
[crayon-5ba2108f600d7374976447/]
[crayon-5ba2108f600dc541411118/]
Do not forget to delete your cache:
[crayon-5ba2108f600e1026385354/]
You should now be able to access the admin dashboard using the following url: http://jobeet.local/app_dev.php/admin/dashboard

The CRUD Controller

The CRUD controller contains the basic CRUD actions. It is related to one Admin class by mapping the controller name to the correct Admin instance. Any or all actions can be overwritten to suit the project’s requirements. The controller uses the Admin class to construct the different actions. Inside the controller, the Admin object is accessible through the configuration property.

Now let’s create a controller for each entity. First, for the Category entity:
[crayon-5ba2108f600e7904981800/]
And now for the Job:
[crayon-5ba2108f600ec729172227/]

Creating the Admin class

The Admin class represents the mapping of your model and administration sections (forms, list, show). The easiest way to create an admin class for your model is to extend the SonataAdminBundleAdminAdmin class. We will create the Admin classes in the Admin folder of our bundle. Start by creating the Admin directory and then, the Admin class for categories:
[crayon-5ba2108f600f2973766426/]
And for jobs:
[crayon-5ba2108f600f8792070326/]
Now we need to add each admin class in the services.yml configuration file:
[crayon-5ba2108f600fd757581559/]
At this point, we can see in the dashboard the Jobeet group and, inside it, the Job and Category modules, with their respective add and list links.Day 12 - sonata_interface

Configuration of Admin classes

If you follow any link right now, nothing will happen. That’s because we haven’t configure the fields that belong to the list and the form. Let’s do a basic configuration, first for the categories:
[crayon-5ba2108f60103185561943/]
And now for jobs:
[crayon-5ba2108f60109757283803/]
For the show action we used a custom template to show the logo of the company:
[crayon-5ba2108f60110471642661/]
With this, we created a basic administration module with operations for our jobs and categories. Some of the features you will find when using it are:

  • The list of objects is paginated
  • The list is sortable
  • The list can be filtered
  • Objects can be created, edited, and deleted
  • Selected objects can be deleted in a batch
  • The form validation is enabled
  • Flash messages give immediate feedback to the user

Batch Actions

Batch actions are actions triggered on a set of selected models (all of them or only a specific subset). You can easily add some custom batch action in the list view. By default, the delete action allows you to remove several entries at once.

To add a new batch action we have to override the getBatchActions from the Admin class. We will define here a new extend action:
[crayon-5ba2108f60117633582263/]
The method batchActionExtend form the JobAdminController will be executed to achieve the core logic. The selected models are passed to the method through a query argument retrieving them. If for some reason it makes sense to perform your batch action without the default selection method (for example you defined another way, at template level, to select model at a lower granularity), the passed query is null.
[crayon-5ba2108f6011d888436430/]
Let’s add a new batch action that will delete all jobs that have not been activated by the poster for more than 60 days. For this action we don’t need to select any jobs from the list because the logic of the action will search for the matching records and delete them.
[crayon-5ba2108f60123557521258/]
In addition to create the batchActionDeleteNeverActivated action, we will create a new method in our JobAdminController, batchActionDeleteNeverActivatedIsRelevant, that gets executed before any confirmation, to make sure there is actually something to confirm (in our case it will always return true because the selection of the jobs to be deleted is handled by the logic found in the JobRepository::cleanup() method.
[crayon-5ba2108f6012a691479748/]

That’s all for today! Tomorrow, we will see how to secure the admin section with a username and a password. This will be the occasion to talk about the symfony2 security.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Symfony2 Jobeet Day 11: Testing your Forms

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.
In day 10, we created our first form with Symfony 2.3. People are now able to post a new job on Jobeet but we ran out of time before we could add some tests. That’s what we will do along these lines.

Submitting a Form

Let’s open the JobControllerTest file to add functional tests for the job creation and validation process. At the end of the file, add the following code to get the job creation page:
[crayon-5ba2108f6191b964795088/]
To select forms we will use the selectButton() method. This method can select button tags and submit input tags. Once you have a Crawler representing a button, call the form() method to get a Form instance for the form wrapping the button node:
[crayon-5ba2108f61927890437284/]

The above example selects an input of type submit using its value attribute “Submit Form".

When calling the form() method, you can also pass an array of field values that overrides the default ones:
[crayon-5ba2108f6192d451550514/]
It is now time to actually select and pass valid values to the form:
[crayon-5ba2108f61932021029388/]
The browser also simulates file uploads if you pass the absolute path to the file to upload.

After submitting the form, we checked that the executed action is create.

Testing the Form

If the form is valid, the job should have been created and the user redirected to the preview page:
[crayon-5ba2108f6193a755616163/]

Testing the Database Record

Eventually, we want to test that the job has been created in the database and check that the is_activated column is set to false as the user has not published it yet.
[crayon-5ba2108f6193f247080725/]

Testing for Errors

The job form creation works as expected when we submit valid values. Let’s add a test to check the behavior when we submit non-valid data:
[crayon-5ba2108f61945489507236/]
Now, we need to test the admin bar found on the job preview page. When a job has not been activated yet, you can edit, delete, or publish the job. To test those three actions, we will need to first create a job. But that’s a lot of copy and paste, so let’s add a job creator method in the JobControllerTest class:
[crayon-5ba2108f6194c918851224/]
The createJob() method creates a job, follows the redirect and returns the browser. You can also pass an array of values that will be merged with some default values.

Testing the Publish action is now more simple:
[crayon-5ba2108f61952763851275/]
Testing the Delete action is quite similar:
[crayon-5ba2108f61958649759641/]

Tests as a SafeGuard

When a job is published, you cannot edit it anymore. Even if the “Edit” link is not displayed anymore on the preview page, let’s add some tests for this requirement.

First, add another argument to the createJob() method to allow automatic publication of the job, and create a getJobByPosition() method that returns a job given its position value:
[crayon-5ba2108f6195e049210774/]
If a job is published, the edit page must return a 404 status code:
[crayon-5ba2108f61965493767237/]
But if you run the tests, you won’t have the expected result as we forgot to implement this security measure yesterday. Writing tests is also a great way to discover bugs, as you need to think about all edge cases.

Fixing the bug is quite simple as we just need to forward to a 404 page if the job is activated:
[crayon-5ba2108f6196b064460845/]

Back to the Future in a Test

When a job is expiring in less than five days, or if it is already expired, the user can extend the job validation for another 30 days from the current date.

Testing this requirement in a browser is not easy as the expiration date is automatically set when the job is created to 30 days in the future. So, when getting the job page, the link to extend the job is not present. Sure, you can hack the expiration date in the database, or tweak the template to always display the link, but that’s tedious and error prone. As you have already guessed, writing some tests will help us one more time.

As always, we need to add a new route for the extend method first:
[crayon-5ba2108f61971327742077/]
Then, replace the Extend link code in the admin.html.twig partial with the extend form:
[crayon-5ba2108f61976382640426/]
Then, create the extend action and the extend form:
[crayon-5ba2108f6197b042135493/]
Also, add the extend form to the preview action:
[crayon-5ba2108f61981586514794/]
As expected by the action, the extend() method of Job returns true if the job has been extended or false otherwise:
[crayon-5ba2108f61987385560469/]
Eventually, add a test scenario:
[crayon-5ba2108f6198c419494624/]

Maintenance Tasks

Even if symfony is a web framework, it comes with a command line tool. You have already used it to create the default directory structure of the application bundle and to generate various files for the model. Adding a new command is quite easy.

When a user creates a job, he must activate it to put it online. But if not, the database will grow with stale jobs. Let’s create a command that remove stale jobs from the database. This command will have to be run regularly in a cron job.
[crayon-5ba2108f61993411804410/]
You will have to add the cleanup method to the JobRepository class:
[crayon-5ba2108f61999644852623/]
To run the command execute the following from the project folder:
[crayon-5ba2108f6199f103659111/]
or:
[crayon-5ba2108f619a4041803362/]
to delete stale jobs older than 10 days.
Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Symfony2 Jobeet Day 10: The Forms

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.
Any website has forms, from the simple contact form to the complex ones with lots of fields. Writing forms is also one of the most complex and tedious task for a web developer: you need to write the HTML form, implement validation rules for each field, process the values to store them in a database, display error messages, repopulate fields in case of errors and much more …

In Day 3 of this tutorial we used the doctrine:generate:crud command to generate a simple CRUD controller for our Job entity. This also generated a Job form that you can find in /src/Ibw/JobeetBundle/Form/JobType.php file.

Customizing the Job Form

The Job form is a perfect example to learn form customization. Let’s see how to customize it, step by step.

First, change the Post a Job link in the layout to be able to check changes directly in your browser:
[crayon-5ba2108f636f9051253493/]
Then, change the ibw_job_show route parameters in createAction of the JobController to match the new route we created in day 5 of this tutorial:
[crayon-5ba2108f63703839880662/]
By default, the Doctrine generated form displays fields for all the table columns. But for the Job form, some of them must not be editable by the end user. Edit the Job form as you see below:
[crayon-5ba2108f6370a799826981/]
The form configuration must sometimes be more precise than what can be introspected from the database schema. For example, the email column is a varchar in the schema, but we need this column to be validated as an email. In Symfony2, validation is applied to the underlying object (e.g. Job). In other words, the question isn’t whether the form is valid, but whether or not the Job object is valid after the form has applied the submitted data to it. To do this, create a new validation.yml file in the Resources/config directory of our bundle:
[crayon-5ba2108f63711831505673/]
Even if the type column is also a varchar in the schema, we want its value to be restricted to a list of choices: full time, part time or freelance.
[crayon-5ba2108f63717155506410/]
For this to work, add the following methods in the Job entity:
[crayon-5ba2108f6371c359977057/]
The getTypes() method is used in the form to get the possible types for a Job and getTypeValues() will be used in the validation to get the valid values for the type field.
[crayon-5ba2108f63721075315546/]
For each field, symfony automatically generates a label (which will be used in the rendered tag). This can be changed with the label option:
[crayon-5ba2108f63727138722740/]
You should also add validation constraints for the rest of the fields:
[crayon-5ba2108f6372c752803073/]
The constraint applied to url field enforces the URL format to be like this: http://www.sitename.domain or https://www.sitename.domain.

After modifying validation.yml, you need to clear the cache.

Handling File Uploads in Symfony2

To handle the actual file upload in the form, we will use a virtual file field. For this, we will add a new file property to the Job entity:
[crayon-5ba2108f63732345649218/]
Now we need to replace the logo with the file widget and change it to a file input tag:
[crayon-5ba2108f63737978460719/]
To make sure the uploaded file is a valid image, we will use the Image validation constraint:
[crayon-5ba2108f6373c654186129/]
When the form is submitted, the file field will be an instance of UploadedFile. It can be used to move the file to a permanent location. After this, we will set the job logo property to the uploaded file name.
[crayon-5ba2108f63741274082180/]
You need to create the logo directory (web/uploads/jobs/) and check that it is writable by the web server.
Even if this implementation works, a better way is to handle the file upload using the Doctrine Job entity.

First, add the following to the Job entity:
[crayon-5ba2108f63747614823554/]
The logo property stores the relative path to the file and is persisted to the database. The getAbsolutePath() is a convenience method that returns the absolute path to the file while the getWebPath() is a convenience method that returns the web path, which can be used in a template to link to the uploaded file.

We will make the implementation so that the database operation and the moving of the file are atomic: if there is a problem persisting the entity or if the file cannot be saved, then nothing will happen. To do this, we need to move the file right as Doctrine persists the entity to the database. This can be accomplished by hooking into the Job entity lifecycle callback. Like we did in day 3 of the Jobeet tutorial, we will edit the Job.orm.yml file and add the preUpload, upload and removeUpload callbacks in it:
[crayon-5ba2108f6374d301990239/]
Now run the generate:entities doctrine command to add these new methods to the Job entity:
[crayon-5ba2108f63752348890384/]
Edit the Job entity and change the added methods to the following:
[crayon-5ba2108f63757334359078/]
The class now does everything we need: it generates a unique filename before persisting, moves the file after persisting, and removes the file if the entity is ever deleted. Now that the moving of the file is handled atomically by the entity, we should remove the code we added earlier in the controller to handle the upload:
[crayon-5ba2108f6375d561651424/]

The Form Template

Now that the form class has been customized, we need to display it. Open the new.html.twig template and edit it:
[crayon-5ba2108f63763179151509/]
We could render the form by just using the following line of code, but as we need more customization, we choose to render each form field by hand.
[crayon-5ba2108f6376d172084538/]
By printing form(form), each field in the form is rendered, along with a label and error message (if there is one). As easy as this is, it’s not very flexible (yet). Usually, you’ll want to render each form field individually so you can control how the form looks.

We also used a technique named form theming to customize how the form errors will be rendered. You can read more about this in the official Symfony2 documentation.

Do the same thing with the edit.html.twig template:
[crayon-5ba2108f63773722777839/]
 

The Form Action

We now have a form class and a template that renders it. Now, it’s time to actually make it work with some actions. The job form is managed by four methods in the JobController:

  • newAction: Displays a blank form to create a new job
  • createAction: Processes the form (validation, form repopulation) and creates a new job with the user submitted values
  • editAction: Displays a form to edit an existing job
  • updateAction: Processes the form (validation, form repopulation) and updates an existing job with the user submitted values

When you browse to the /job/new page, a form instance for a new job object is created by calling the createForm() method and passed to the template (newAction).

When the user submits the form (createAction), the form is bound (bind($request) method) with the user submitted values and the validation is triggered.

Once the form is bound, it is possible to check its validity using the isValid() method: if the form is valid (returns true), the job is saved to the database ($em->persist($entity)), and the user is redirected to the job preview page; if not, the new.html.twig template is displayed again with the user submitted values and the associated error messages.

The modification of an existing job is quite similar. The only difference between the new and the edit action is that the job object to be modified is passed as the second argument of the createForm method. This object will be used for default widget values in the template.

You can also define default values for the creation form. For this we will pass a pre-modified Job object to the createForm() method to set the type default value to full-time:
[crayon-5ba2108f6377e821870299/]

PROTECTING THE JOB FORM WITH A TOKEN

Everything must work fine by now. As of now, the user must enter the token for the job. But the job token must be generated automatically when a new job is created, as we don’t want to rely on the user to provide a unique token. Add the setTokenValue method to the prePersist lifecycleCallbacks for the Job entity:
[crayon-5ba2108f63784080674626/]
Regenerate the doctrine entities to apply this modification:
[crayon-5ba2108f6378a523877661/]
Edit the setTokenValue() method of the Job entity to add the logic that generates the token before a new job is saved:
[crayon-5ba2108f6378e445300227/]
You can now remove the token field from the form:
[crayon-5ba2108f63793937302535/]
Remove it from the new.html.twig and edit.html.twig templates also:
[crayon-5ba2108f63799014305606/]
[crayon-5ba2108f6379e450423808/]
And from the validation.yml file:
[crayon-5ba2108f637a3954596864/]
If you remember the user stories from day 2, a job can be edited only if the user knows the associated token. Right now, it is pretty easy to edit or delete any job, just by guessing the URL. That’s because the edit URL is like /job/ID/edit, where ID is the primary key of the job.

Let’s change the routes so you can edit or delete a job only if you now the secret token:
[crayon-5ba2108f637a8059246171/]
Now edit the JobController to use the token instead of the id:
[crayon-5ba2108f637ad157650502/]
In the job show template show.html.twig, change the ibw_job_edit route parameter:
[crayon-5ba2108f637b4873120005/]
Do the same for ibw_job_update route in edit.html.twig job template:
[crayon-5ba2108f637ba742330520/]
Now, all routes related to the jobs, except the job_show_user one, embed the token. For instance, the route to edit a job is now of the following pattern:
http://jobeet.local/job/TOKEN/edit

The Preview Page

The preview page is the same as the job page display. The only difference is that the job preview page will be accessed using the job token instead of the job id:
[crayon-5ba2108f637bf040149142/]
The preview action (here the difference from the show action is that the job is retrieved from the database using the provided token instead of the id):
[crayon-5ba2108f637c4149829818/]
If the user comes in with the tokenized URL, we will add an admin bar at the top. At the beginning of the show.html.twig template, include a template to host the admin bar and remove the edit link at the bottom:
[crayon-5ba2108f637c9817245663/]
Then, create the admin.html.twig template:
[crayon-5ba2108f637ce255580338/]
There is a lot of code, but most of the code is simple to understand.

To make the template more readable, we have added a bunch of shortcut methods in the Job entity class:
[crayon-5ba2108f637d5984963970/]
The admin bar displays the different actions depending on the job status:

Day 10 - admin bar

Day 10 -admin badr 2

We will now redirect the create and update actions of the JobController to the new preview page:
[crayon-5ba2108f637da778454399/]
As we said before, you can edit a job only if you know the job token and you’re the admin of the site. At the moment, when you access a job page, you will see the Edit link and that’s bad. Let’s remove it from the show.html.twig file:
[crayon-5ba2108f637e1019518861/]

Job Activation and Publication

In the previous section, there is a link to publish the job. The link needs to be changed to point to a new publish action. For this we will create new route:
[crayon-5ba2108f637e7468753900/]
We can now change the link of the Publish link (we will use a form here, like when deleting a job, so we will have a POST request):
[crayon-5ba2108f637ec605971438/]
The last step is to create the publish action, the publish form and to edit the preview action to send the publish form to the template:
[crayon-5ba2108f637f1267297524/]
The publishAction() method uses a new publish() method that can be defined as follows:
[crayon-5ba2108f637f7899468474/]
You can now test the new publish feature in your browser.

But we still have something to fix. The non-activated jobs must not be accessible, which means that they must not show up on the Jobeet homepage, and must not be accessible by their URL. We need to edit the JobRepository methods to add this requirement:
[crayon-5ba2108f637fc180470745/]
The same for CategoryRepository getWithJobs() method:
[crayon-5ba2108f63803838629957/]

That’s all. You can test it now in your browser. All non-activated jobs have disappeared from the homepage; even if you know their URLs, they are not accessible anymore. They are, however, accessible if one knows the job’s token URL. In that case, the job preview will show up with the admin bar.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Symfony2 Jobeet Day 9: The functional Tests

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.
Functional tests are a great tool to test your application from end to end: from the request made by a browser to the response sent by the server. They test all the layers of an application: the routing, the model, the actions and the templates. They are very similar to what you probably already do manually: each time you add or modify an action, you need to go to the browser and check that everything works as expected by clicking on links and checking elements on the rendered page. In other words, you run a scenario corresponding to the use case you have just implemented.

As the process is manual, it is tedious and error prone. Each time you change something in your code, you must step through all the scenarios to ensure that you did not break something. That’s insane. Functional tests in symfony provide a way to easily describe scenarios. Each scenario can then be played automatically over and over again by simulating the experience a user has in a browser. Like unit tests, they give you the confidence to code in peace.

Functional tests have a very specific workflow:

  • Make a request;
  • Test the response;
  • Click on a link or submit a form;
  • Test the response;
  • Rinse and repeat;

Our First Functional Test

Functional tests are simple PHP files that typically live in the Tests/Controller directory of your bundle. If you want to test the pages handled by your CategoryController class, start by creating a new CategoryControllerTest class that extends a special WebTestCase class:
[crayon-5ba2108f6647a286339400/]
To learn more about crawler, read the Symfony documentation here.

Running Functional Tests

As for unit tests, launching functional tests can be done by executing the phpunit command:
[crayon-5ba2108f66488104255693/]
This test will fail because the tested url, /category/index, is not a valid url in Jobeet:
[crayon-5ba2108f6648d730067750/]

Writing Functional Tests

Writing functional tests is like playing a scenario in a browser. We already have written all the scenarios we need to test as part of the day 2 stories.

First, let’s test the Jobeet homepage by editing the JobControllerTest class. Replace the code with the following one:

EXPIRED JOBS ARE NOT LISTED

[crayon-5ba2108f66493955054174/]
To verify the exclusion of expired jobs from the homepage, we check that the CSS selector .jobs td.position:contains("Expired") does not match anywhere in the response HTML content (remember that in the fixtures, the only expired job we have contains “Expired” in the position).

ONLY N JOBS ARE LISTED FOR A CATEGORY

Add the following code at the end of your testIndex() function. To get the custom parameter defined in app/config/config.yml in our functional test, we will use the kernel:
[crayon-5ba2108f6649b478096356/]
For this test to work we will need to add the corresponding CSS class to each category in the Job/index.html.twig file (so we can select each category and count the jobs listed) :
[crayon-5ba2108f664a1431702745/]

A CATEGORY HAS A LINK TO THE CATEGORY PAGE ONLY IF TOO MANY JOBS

[crayon-5ba2108f664a6708167110/]
In these tests, we check that there is no “more jobs” link for the design category (.category_design .more_jobs does not exist), and that there is a “more jobs” link for the programming category (.category_programming .more_jobs does exist).

JOBS ARE SORTED BY DATE

To test if jobs are actually sorted by date, we need to check that the first job listed on the homepage is the one we expect. This can be done by checking that the URL contains the expected primary key. As the primary key can change between runs, we need to get the Doctrine object from the database first.
[crayon-5ba2108f664ac440391753/]
Even if the test works in this very moment, we need to refactor the code a bit, as getting the first job of the programming category can be reused elsewhere in our tests. We won’t move the code to the Model layer as the code is test specific. Instead, we will move the code to the getMostRecentProgrammingJob function in our test class:
[crayon-5ba2108f664b2265233063/]
You can now replace the previous test code by the following one:
[crayon-5ba2108f664b7872232692/]

EACH JOB ON THE HOMEPAGE IS CLICKABLE

To test the job link on the homepage, we simulate a click on the “Web Developer” text. As there are many of them on the page, we have explicitly to ask the browser to click on the first one.

Each request parameter is then tested to ensure that the routing has done its job correctly.
[crayon-5ba2108f664bd538574313/]

LEARN BY THE EXAMPLE

In this section, you have all the code needed to test the job and category pages. Read the code carefully as you may learn some new neat tricks:
[crayon-5ba2108f664c3364844626/]
 
[crayon-5ba2108f664cd175086510/]

That’s all for today! Tomorrow, we will learn all there is to know about forms.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Symfony2 Jobeet Day 8: The Unit Tests

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.

Tests in Symfony

There are two different kinds of automated tests in Symfony: unit tests and functional tests. Unit tests verify that each method and function is working properly. Each test must be as independent as possible from the others. On the other hand, functional tests verify that the resulting application behaves correctly as a whole.

Unit tests will be covered in this post, whereas the next post will be dedicated to funcional tests.

Symfony2 integrates with an independent library, the PHPUnit, to give you a rich testing framework. To run tests, you will have to install PHPUnit 3.5.11 or later.

If you don’t have PHPUnit installed, use the following to get it:

[crayon-5ba2108f6783a104182554/]

Each test – whether it’s a unit test or a functional test – is a PHP class that should live in the Tests/ subdirectory of your bundles. If you follow this rule, then you can run all of your application’s tests with the following command:

[crayon-5ba2108f67846769449642/]

The -c option tells PHPUnit to look in the app/ directory for a configuration file. If you’re curious about the PHPUnit options, check out the app/phpunit.xml.dist file.

A unit test is usually a test against a specific PHP class. Let’s start by writing tests for the Jobeet:slugify() method.

Create a new file, JobeetTest.php, in the src/Ibw/JobeetBundle/Tests/Utils folder. By convention, the Tests/ subdirectory should replicate the directory of your bundle. So, when we are testing a class in our bundle’s Utils/ directory, we put the test in the Tests/Utils/ directory:

[crayon-5ba2108f6784c346741452/]

To run only this test, you can use the following command:

[crayon-5ba2108f67852503133515/]

As everything should work fine, you should get the following result:

[crayon-5ba2108f67857994048941/]

For a full list of assertions, you can check the PHPUnit documentation.

Adding Tests for new Features

The slug for an empty string is an empty string. You can test it, it will work. But an empty string in a URL is not that a great idea. Let’s change the slugify() method so that it returns the “n-a” string in case of an empty string.

You can write the test first, then update the method, or the other way around. It is really a matter of taste, but writing the test first gives you the confidence that your code actually implements what you planned:

[crayon-5ba2108f6785d293143966/]

Now, if we run the test again, we will have a failure:

[crayon-5ba2108f67862063889843/]

Now, edit the Jobeet::slugify method and add the following condition at the beginning:

[crayon-5ba2108f67867666714083/]

The test must now pass as expected, and you can enjoy the green bar.

Adding Tests because of a Bug

Let’s say that time has passed and one of your users reports a weird bug: some job links point to a 404 error page. After some investigation, you find that for some reason, these jobs have an empty company, position, or location slug.

How is it possible?

You look through the records in the database and the columns are definitely not empty. You think about it for a while, and bingo, you find the cause. When a string only contains non-ASCII characters, the slugify() method converts it to an empty string. So happy to have found the cause, you open the Jobeet class and fix the problem right away. That’s a bad idea. First, let’s add a test:

[crayon-5ba2108f6786d130787583/]

After checking that the test does not pass, edit the Jobeet class and move the empty string check to the end of the method:

[crayon-5ba2108f67872471987441/]

The new test now passes, as do all the other ones. The slugify() had a bug despite our 100% coverage.

You cannot think about all edge cases when writing tests, and that’s fine. But when you discover one, you need to write a test for it before fixing your code. It also means that your code will get better over time, which is always a good thing.

Towards a better slugify Method

You probably know that symfony has been created by French people, so let’s add a test with a French word that contains an “accent”:

[crayon-5ba2108f67878700717390/]

The test must fail. Instead of replacing é by e, the slugify() method has replaced it by a dash (-). That’s a tough problem, called transliteration. Hopefully, if you have iconv Library installed, it will do the job for us. Replace the code of the slugify method with the following:

The test must fail. Instead of replacing é by e, the slugify() method has replaced it by a dash (-). That’s a tough problem, called transliteration. Hopefully, if you have iconv Library installed, it will do the job for us. Replace the code of the slugify method with the following:

[crayon-5ba2108f6787d074001259/]

Remember to save all your PHP files with the UTF-8 encoding, as this is the default Symfony encoding, and the one used by iconv to do the transliteration.

Also change the test file to run the test only if iconv is available:

[crayon-5ba2108f67883581283610/]

Code Coverage

When you write tests, it is easy to forget a portion of the code. If you add a new feature or you just want to verify your code coverage statistics, all you need to do is to check the code coverage by using the --coverage-html option:

[crayon-5ba2108f67888936273951/]

Check the code coverage by opening the generated http://jobeet.local/cov/index.html page in a browser.
The code coverage only works if you have XDebug enabled and all dependencies installed. 

[crayon-5ba2108f6788e116592613/]

Your cov/index.html should look like this:

day 8 - code coverage1

Keep in mind that when this indicates that your code is fully unit tested, it just means that each line has been executed, not that all the edge cases have been tested.

Doctrine Unit Tests

Unit testing a Doctrine model class is a bit more complex as it requires a database connection. You already have the one you use for your development, but it is a good habit to create a dedicated database for tests.

At the beginning of this tutorial, we introduced the environments as a way to vary an application’s settings. By default, all symfony tests are run in the test environment, so let’s configure a different database for the test environment:

Go to your app/config directory and create a copy of parameters.yml file, called parameters_test.yml. Open parameters_test.yml and change the name of your database to jobeet_test. For this to be imported, we have to add it in the config_test.yml file :

[crayon-5ba2108f67894282961175/]

Testing the Job Entity

First, we need to create the JobTest.php file in the Tests/Entity folder.

The setUp function will manipulate your database each time you will run the test. At first, it will drop your current database, then it will re-create it and load data from fixtures in it. This will help you have the same initial data in the database you created for the test environment before running the tests.

[crayon-5ba2108f67899024033673/]

Testing the Repository Classes

Now, let’s write some tests for the JobRepository class, to see if the functions we created in the previous days are returning the right values:

[crayon-5ba2108f678a2367199314/]

We will do the same thing for CategoryRepository class:

[crayon-5ba2108f678ac459137833/]

After you finish writing the tests, run them with the following command, in order to generate the code coverage percent for the whole functions :

[crayon-5ba2108f678b4220187383/]

Now, if you go to http://jobeet.local/cov/Repository.html you will see that the code coverage for Repository Tests is not 100% complete.

Day 8 - coverage not complete

Let’s add some tests for the JobRepository to achieve 100% code coverage. At the moment, in our database, we have two job categories having 0 active jobs and one job category having just one active job. That why, when we will test the $max and $offset parameters, we will run the following tests just on the categories with at least 3 active jobs. In order to do that, add this inside your foreach statement, from your testGetActiveJobs() function:

[crayon-5ba2108f678bb702234306/]

Run the code coverage command again :

[crayon-5ba2108f678c1080302853/]

This time, if you check your code coverage, you will see that it 100% complete.

Day 8 - coverage complete

That’s all for today! See you tomorrow, when we will talk about functional tests.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Symfony2 Jobeet Day 7: Playing with the Category page

* This article is part of the original Jobeet Tutorial, created by Fabien Potencier, for Symfony 1.4.
Today we will make the Category page like it is described in the second day’s requirements:

“The user sees a list of all the jobs from the category sorted by date and paginated with 20 jobs per page“

The Category Route

First, we need to add a route to define a pretty URL for the category page. Add it at the beginning of the routing file:
[crayon-5ba2108f693e5090035697/]
To get the slug of a category we need to add the getSlug() method to our category class:
[crayon-5ba2108f693f0572063641/]

The Category Link

Now, edit the index.html.twig template of the job controller to add the link to the category page:
[crayon-5ba2108f693f6259976722/]
In the template above we used category.morejobs, so let’s define it:
[crayon-5ba2108f693fb769217111/]
The more_jobs property will hold the number of active jobs for the category minus the number of jobs listed on the homepage. Now, in JobController, we need to set the more_jobs value for each category:
[crayon-5ba2108f69401038684925/]
The countActiveJobs function has to be added to the JobRepository:
[crayon-5ba2108f69407282200954/]
Now you should see the result in your browser:

Day-7 - category link

Category Controller Creation

It’s now time to create the Category controller. Create a new CategoryController.php file in your Controller directory:
[crayon-5ba2108f6940c100914778/]
We could use the doctrine:generate:crud command like we did for the job controller, but we won’t need 90% of the generated code, so we can just create a new controller from scratch.

Update the Database

We need to add a slug column for the category table and lifecycle callbacks for setting this column value:
[crayon-5ba2108f69412960983950/]
Remove from the Category entity (src/Ibw/JobeetBundle/Entity/Category.php) the getSlug method we created earlier and run the doctrine command to update the Category entity class:
[crayon-5ba2108f69418412426428/]
Now you should have the following added to Category.php:
[crayon-5ba2108f6941d282207676/]
Change the setSlugValue() function:
[crayon-5ba2108f69422399957931/]
Now we have to drop the database and create it again with the new Category column and load the fixtures:
[crayon-5ba2108f69427977921880/]

Category Page

We have now everything in place to create the showAction() method. Add the following code to the CategoryController.php file:
[crayon-5ba2108f6942c764304992/]
The last step is to create the show.html.twig template:
[crayon-5ba2108f69432530756057/]

Including Other Twig Templates

Notice that we have copied and pasted the tag that create a list of jobs from the job index.html.twig template. That’s bad. When you need to reuse some portion of a template, you need to create a new twig template with that code and include it where you need. Create the list.html.twig file:
[crayon-5ba2108f69438040527098/]
You can include a template by using the include function. Replace the HTML <table> code from both templates with the mentioned function:
[crayon-5ba2108f6943e683362102/]
[crayon-5ba2108f69443698596054/]

List Pagination

At the moment of writing this, Symfony2 doesn’t provide any good pagination tools out of the box so to solve this problem we will use the old classic method. First, let’s add a page parameter to the IbwJobeetBundle_category route. The page parameter will have a default value of 1, so it will not be required:

[crayon-5ba2108f69448783076243/]

Clear the cache after modifying the routing file:

[crayon-5ba2108f6944d860349724/]

The number of jobs on each page will be defined as a custom parameter in the app/config/config.yml file:

[crayon-5ba2108f69452129021619/]

Change the JobRepository getActiveJobs method to include an $offset parameter to be used by doctrine when retrieving jobs:

[crayon-5ba2108f69457713472053/]

Change the CategoryController showAction to the following:

[crayon-5ba2108f6945c571631402/]

Finally, let’s update the template

[crayon-5ba2108f69462450231196/]

The result:

Day 7 - pagination
Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.