Symfony2: raw form data access in validator

I created my own validator for the Symfony2 form. It is called ValidDateValidator, and it should filter out invalid dates, e.g. 2015-02-31. The type of the form is as follows:

->add(
        'thedate',
        DateType::class,
        array(
            'widget' => 'single_text',
            'format' => 'yyyy-MM-dd',
            'constraints' => array(
                new ValidDate()
            )
        )
)

now if i try to access this in my validator as follows:

public function validate($value, Constraint $constraint){
    //this returns 2015-03-03 
    echo $value->format('Y-m-d'); 
}

As a result, I get "2015-03-03". Is there a way to access raw form data without processing it?

+4
source share
2 answers

Unfortunately this is not possible. Validators get their data after data conversion .

, . . DateField DateTime-Object.

, . , invalid_message DateField.

:

:

namespace AppBundle\Form\DataTransformer;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class StringToDateTransformer implements DataTransformerInterface
{  
    /**
     * Transforms a DateTime object to a string .
     *
     * @param  DateTime|null $date
     * @return string
     */
    public function transform($date)
    {
        if (null === $date) {
            return '';
        }

        return $date->format('Y-m-d');
    }

    /**
     * Transforms a string to a DateTime object.
     *
     * @param  string $dateString
     * @return DateTime|null
     * @throws TransformationFailedException if invalid format/date.
     */
    public function reverseTransform($dateString)
    {
        //Here do what ever you would like to do to transform the string to 
        //a DateType object
        //The important thing is to throw an TransformationFailedException
        //if something goes wrong (such as wrong format, or invalid date):

        throw new TransformationFailedException('The date is incorrect!');

        return $dateTime;
    }
}

:

$builder->get('thedate')
            //Important!
            ->resetViewTransformers()
            ->addViewTransformer(new StringToDateTransformer());

resetViewTransformers(). , DateType, . , , .

+2

\DateTime:: . , .

checkdate, , .

$dateString = '2015-2-31';

$bits = explode('-', $dateString); // split the string
list($y, $m, $d) = $bits; // variablise the parts

if(checkdate($m, $d, $y)) {
    // do something
} else {
    // do something else
}

+1

Source: https://habr.com/ru/post/1650506/


All Articles