Php 使用Symfony2中的Form Builder将对象替换为空值
我在持久化一个空值时遇到问题,这个空值已经被一个对象持久化了 它抛出以下错误Php 使用Symfony2中的Form Builder将对象替换为空值,php,symfony,doctrine-orm,bind,formbuilder,Php,Symfony,Doctrine Orm,Bind,Formbuilder,我在持久化一个空值时遇到问题,这个空值已经被一个对象持久化了 它抛出以下错误 Catchable Fatal Error: Argument 1 passed to MyProject\EntityBundle\Entity\Requirements::setReplacedEmployee() must be an instance of MyProject\EntityBundle\Entity\Employee, null given, called in /var/www/MyProje
Catchable Fatal Error: Argument 1 passed to MyProject\EntityBundle\Entity\Requirements::setReplacedEmployee() must be an instance of MyProject\EntityBundle\Entity\Employee, null given, called in /var/www/MyProject/vendor/symfony/src/Symfony/Component/Form/Util/PropertyPath.php on line 347 and defined in /var/www/MyProject/src/MyProject/EntityBundle/Entity/Requirements.php line 384
最初,我保存replacedEmployee对象,它可以是null/object。但稍后,如果我在编辑时将对象替换为null,则会抛出上述错误
下面是我的控制器代码
try {
if ($request->request->get('save') === 'Save') {
$form->bindRequest($request); // this is the line which throws the above error
if ($form->isValid()) {
$requirementObj->setUpdatedAt(new \DateTime('now'));
$em->flush();
$request->request->set('requirementId', $requirementId);
return $this->displayAction($request);
}
}
}
这是Requirements.php中的内容,它是一个实体文件
/**
* @var replacedEmployee
*
* @ORM\ManyToOne(cascade={"persist"},targetEntity="Employee")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="replaced_employee_id",referencedColumnName="id",onDelete="CASCADE")
* })
*/
private $replacedEmployee;
/**
* Set replacedEmployee
*
* @param MyProject\EntityBundle\Entity\Employee $replacedEmployee
*/
public function setReplacedEmployee(\MyProject\EntityBundle\Entity\Employee $replacedEmployee)
{
$this->replacedEmployee = $replacedEmployee;
}
/**
* Get replacedEmployee
*
* @return MyProject\EntityBundle\Entity\Employee
*/
public function getReplacedEmployee()
{
return $this->replacedEmployee;
}
有人能提出解决这个问题的办法吗
提前谢谢。我不能完全理解您的问题,但是,如果您想允许
null
值用于与员工的关系,您应该首先编辑映射(这可能不是必需的,因为JoinColumn
默认情况下应该允许null
值):
在生成setters/getters Doctrine2(如果我没记错的话,从2.2.1开始)之后,应该生成:
/**
* Set replacedEmployee
*
* @param MyProject\EntityBundle\Entity\Employee $replacedEmployee
*/
public function setReplacedEmployee(Employee $replacedEmployee = null)
{
$this->replacedEmployee = $replacedEmployee;
}
请注意,参数是可选的(具有null
默认值)。希望这能有所帮助。我已经按照您的要求添加了一些代码。您在Requirements中调用了Requirements::setReplacedEmployee()
。php
Requirements是一个实体文件。其中包含函数setReplacedEmployee()。当控制器执行$form->bindRequest($request)时,自动调用该函数;格雷莫,你刚刚为我节省了很多时间(谢谢!投票表决。
/**
* Set replacedEmployee
*
* @param MyProject\EntityBundle\Entity\Employee $replacedEmployee
*/
public function setReplacedEmployee(Employee $replacedEmployee = null)
{
$this->replacedEmployee = $replacedEmployee;
}