使用Symfony2将实体字段编辑为null


Edit entity field to null using Symfony2

如果Entity字段以前有值,则在将该字段编辑为NULL时出错。对于第一次持久化到数据库,我可以用NULL值提交它。将值更改回NULL时发生此错误:

可捕获的致命错误:参数1传递给Sifo''SharedBundle''Entity''BlogMenu::setBlogPage()必须是一个实例的Sifo''SharedBundle''Entity''BlogPage,给定null,在中调用C: ''Sifony''vendor''symfony''symfony ''src''symfony''Component''PropertyAccess''PropertyAAccessor.php第438行,定义于C: ''Sifony''src''Sifo''SharedBundle''Entity''BlogMenu.php第332行

这是我的实体BlogMenu.php第332行:

// ...
 * Set blogPage
 *
 * @param 'Sifo'SharedBundle'Entity'BlogPage $blogPage
 * @return blogPage
 */
public function setBlogPage('Sifo'SharedBundle'Entity'BlogPage $blogPage) // Line 332
{
    $this->blogPage = $blogPage;
    return $this;
}
/**
 * Get blogPage
 *
 * @return 'Sifo'SharedBundle'Entity'BlogPage 
 */
public function getBlogPage()
{
    return $this->blogPage;
}
// ...

updateAction在我的控制器中是这样的:

/**
 * Edits an existing BlogMenu entity.
 *
 */
public function updateAction(Request $request, $id)
{
    $user = $this->getUser();
    $em = $this->getDoctrine()->getManager();
    $entity = $em->getRepository('SifoSharedBundle:BlogMenu')->find($id);
    if (!$entity) {
        throw $this->createNotFoundException('Unable to find BlogMenu entity.');
    }
    $entity->setOperator($user->getName());
    $form = $this->createEditForm($entity);
    $form->handleRequest($request);
    if ($form->isValid()) {
        $em->flush();
        return $this->redirect($this->generateUrl('admin_blog_menu_show', array('id' => $id)));
    }
    return $this->render('SifoAdminBundle:edit:layout.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
        'user'   => $user,
    ));
}

这是我的FormType:

<?php
// ...
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('blog_page', 'entity', array(
                'required' => false, 
                'empty_value' => 'admin.choice.choosePage',
                'class' => 'Sifo'SharedBundle'Entity'BlogPage'))
// ...

将代码修改为此

public function setBlogPage('Sifo'SharedBundle'Entity'BlogPage $blogPage = null) 
{
    $this->blogPage = $blogPage;
    return $this;
}

正如我在评论中告诉你的,这是由于类型暗示。类型提示用于检查传递给函数的参数的类型(类;而不是基元类型,您可以检查此答案)。如果你想让你的函数接受null类型,你应该指定它。

最好使用类型暗示,因为它"更安全",不会造成"副作用"(如果可能的话)。让我们考虑一下第三方库或供应商:如果您使用第三方库中的函数,您应该知道参数类型,如果您试图传递错误的类型,"编译器"(解析器)会通知您。

我不确定这是否是解决这个问题的好方法。我在entity中删除了作为实体的变量声明。

 * Set blogPage
 *
 * @param 'Sifo'SharedBundle'Entity'BlogPage $blogPage
 * @return blogPage
 */
public function setBlogPage($blogPage) // Line 332
{
    $this->blogPage = $blogPage;
    return $this;
}

在我的案例中,问题出现在php.ini max_input_vars变量中。默认情况下是1000,但我发送了3k+
这两种想法都不好:允许null并删除声明