1

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?

4 Answers 4

2

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])
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

How is it even related to the topic?
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.