user2394156
user2394156

Reputation: 1840

Symfony2 particular data transformer

I have an entity Calendar with dateFrom and dateTo properties.

Now in my form I have one hidden input with date formatted like this: 2010-01-01,2011-01-01.

How can I write a data transformer in Symfony2 which will allow me to transform this date to TWO properties?

Upvotes: 1

Views: 1135

Answers (4)

dphoyes
dphoyes

Reputation: 26

I solved a similar problem by adding a custom getter/setter to my entity (for example, getDateIntervalString and setDateIntervalString). The getter converts dateTo and dateFrom into the interval string and returns it, and the setter accepts a similarly formatted string and uses it to set dateTo and dateFrom. Then, add the field to the form like this:

$builder->add('dates', 'text', ['property_path' => 'date_interval_string'])

By overriding the property path, your custom getter and setter will be used.

Upvotes: 0

martti
martti

Reputation: 2075

If it's possible, use 2 hidden fields. Then use a DateTime to String datatransformer on each field. Then your form is logically mapped to your entity.

Upvotes: 0

I think that the transformer himself has nothing to do with the "properties", it just handle transformation from a data structure to another data structure. You just have to handle the new data structure on your code base.

The transformer himself might look like this :

class DateRangeArrayToDateRangeStringTransformer implements DataTransformerInterface
{
    /**
     * Transforms an array of \DateTime instances to a string of dates.
     *
     * @param  array|null $dates
     * @return string
     */
    public function transform($dates)
    {
        if (null === $dates) {
            return '';
        }

        $datesStr = $dates['from']->format('Y-m-d').','.$dates['to']->format('Y-m-d');

        return $datesStr;
    }

    /**
     * Transforms a string of dates to an array of \DateTime instances.
     *
     * @param  string $datesStr
     * @return array
     */
    public function reverseTransform($datesStr)
    {
        $dates = array();
        $datesStrParts = explode(',', $datesStr);

        return array(
            'from' => new \DateTime($datesStrParts[1]),
            'to'   => new \DateTime($datesStrParts[2])
        );
    }
}

Upvotes: 2

rpg600
rpg600

Reputation: 2850

You can use the explode function like that :

$dates = explode(",", "2010-01-01,2011-01-01");
echo $dates[0]; // 2010-01-01
echo $dates[1]; // 2011-01-01

Then create two new DateTime.

Upvotes: 0

Related Questions