* 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:

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:

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:

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:

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.

For this to work, add the following methods in the Job entity:

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.

For each field, symfony automatically generates a label (which will be used in the rendered tag). This can be changed with the label option:

You should also add validation constraints for the rest of the fields:

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:

Now we need to replace the logo with the file widget and change it to a file input tag:

To make sure the uploaded file is a valid image, we will use the Image validation constraint:

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.

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:

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:

Now run the generate:entities doctrine command to add these new methods to the Job entity:

Edit the Job entity and change the added methods to the following:

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:

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:

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.

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:

 

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:

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:

Regenerate the doctrine entities to apply this modification:

Edit the setTokenValue() method of the Job entity to add the logic that generates the token before a new job is saved:

You can now remove the token field from the form:

Remove it from the new.html.twig and edit.html.twig templates also:

And from the validation.yml file:

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:

Now edit the JobController to use the token instead of the id:

In the job show template show.html.twig, change the ibw_job_edit route parameter:

Do the same for ibw_job_update route in edit.html.twig job template:

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:

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):

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:

Then, create the admin.html.twig template:

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:

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:

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:

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:

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):

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:

The publishAction() method uses a new publish() method that can be defined as follows:

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:

The same for CategoryRepository getWithJobs() method:

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.