Book Image

Symfony2 Essentials

Book Image

Symfony2 Essentials

Overview of this book

Table of Contents (17 chapters)
Symfony2 Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Transforming data


When we created our TaskType class, we skipped the tags property as this was not a simple text or date field. The tags property is related to the Tag table with the M:N relation, so we could present it as a list of checkboxes or a select box. However, people are used to fill tags with comma-separated values, so let's try to convert our objects to comma-separated tag names when displaying a field and convert them back when saving data to the database.

To present a list of objects (tags) as comma-separated values and to convert them back to tags, we need to create a data transformer. A data transformer is a class implementing DataTransformerInterface and allows us to transform our data to various formats. As an example—a data transformer is used when the date or date/time field type is used.

Create a src/AppBundle/Form/DataTransformer/TagDataTransformer.php file as follows:

<?php

namespace AppBundle\Form\DataTransformer;

use AppBundle\Entity\Tag;
use Doctrine\ORM\EntityManager...