Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 DateTime null accept

So, I want to be able send a null option to my DOB field.

Here is my form builder:

->add('birthDate', DateType::class, array(
                'widget' => 'single_text',
                'format' => 'yyyy-MM-dd'))

And here is those field in my entity

 /**
     * @ORM\Column(
     *     type="date",
     *     nullable=true
     * )
     * @JMS\Groups("single")
     *
     * @var \DateTime
     */
    protected $birthDate;

When I`m trying to send a null I got an error msg

Expected argument of type "DateTime", "NULL" given

any ideas?

CRITICAL - Uncaught PHP Exception Symfony\Component\PropertyAccess\Exception\InvalidArgumentException: "Expected argument of type "DateTime", "NULL" given" at /var/www/server.local/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php line 253 



  $type = $trace[$i]['args'][0];
    $type = is_object($type) ? get_class($type) : gettype($type);
    throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given', substr($message, $pos, strpos($message, ',', $pos) - $pos), $type));
}

}

like image 214
Lunin Roman Avatar asked Apr 13 '16 12:04

Lunin Roman


3 Answers

Don't pass any values to it. Make the field not required by doing this:

->add(
    'birthDate', 
    DateType::class, 
    array(
        'required' => false,
        'widget' => 'single_text',
        'format' => 'yyyy-MM-dd'
    )
)
like image 93
LMS94 Avatar answered Oct 31 '22 18:10

LMS94


The problem occurs due type-hinted setter as it is mentioned in the comments. There are two solutions:

1. Use 'by_reference' => true on your form:

$builder->add(
    'birthDate',
    DateType::class,
    [
        'widget' => 'single_text',
        'format' => 'yyyy-MM-dd',
        'by_reference' => true,
    ]
);

2. Let your setter accept null:

public function setBirthDate(\DateTime $value = null)
{
   .....
}
like image 42
Aistis Avatar answered Oct 31 '22 19:10

Aistis


In this case, the problem was caused by PHP type hinting. If you use type hinting (for instance setBirthDate(\DateTime $value)) then PHP forces you that you actually provide a DateTime object. Obviously, null is not such an object. To resolve this problem, it is possible to give $value a default value like this: setBirthDate(\DateTime $value = null).

This is documented behavior and explained in the PHP Documentation (http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration).

Relevant passage:

To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.

like image 27
Emanuel Oster Avatar answered Oct 31 '22 18:10

Emanuel Oster