Lun*_*man 7 datetime doctrine symfony
所以,我希望能够向我的DOB字段发送一个null选项.
这是我的表单构建器:
->add('birthDate', DateType::class, array(
'widget' => 'single_text',
'format' => 'yyyy-MM-dd'))
Run Code Online (Sandbox Code Playgroud)
这是我实体中的那些领域
/**
* @ORM\Column(
* type="date",
* nullable=true
* )
* @JMS\Groups("single")
*
* @var \DateTime
*/
protected $birthDate;
Run Code Online (Sandbox Code Playgroud)
当我试图发送空值时,我收到了错误信息
Expected argument of type "DateTime", "NULL" given
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
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));
}
Run Code Online (Sandbox Code Playgroud)
}
Ema*_*ter 18
在这种情况下,问题是由PHP类型提示引起的.如果您使用类型提示(例如setBirthDate(\DateTime $value)),那么PHP会强制您实际提供DateTime对象.显然,null不是这样的对象.要解决此问题,可以提供如下$value默认值:setBirthDate(\DateTime $value = null).
这是记录在案的行为,并在PHP文档中进行了解释(http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration).
相关段落:
要指定类型声明,应在参数名称之前添加类型名称.如果参数的默认值设置为NULL,则可以使声明接受NULL值.
问题是由于注释中提到的类型提示设置器而发生的。有两种解决方案:
1.'by_reference' => true在你的表格上使用:
$builder->add(
'birthDate',
DateType::class,
[
'widget' => 'single_text',
'format' => 'yyyy-MM-dd',
'by_reference' => true,
]
);
Run Code Online (Sandbox Code Playgroud)
2.让你的二传手接受null:
public function setBirthDate(\DateTime $value = null)
{
.....
}
Run Code Online (Sandbox Code Playgroud)