1

我正在使用 symfony2 框架开发一个网站,并使用 Doctrine 作为我的 ORM。我有两个实体形成一个简单的双向 OneToMany 关系,一侧是 Category,多侧是 Entry。为了让用户管理类别和相应的条目,我使用了 SonataAdminBundle。我还在管理包中实现了一个简单的文件上传。每当我尝试保存新条目时,都会出现以下错误:

An exception occurred while executing 'INSERT INTO Entry
(title, ent_text, img, author,  pub_date, slug, cat_id) VALUES (?, ?, ?, ?, ?, ?, ?)'
with params ["BLa", null, "asdf.jpg", "User", null, "bla", 1]:

我完全不知道这是从哪里来的,尤其是因为表格中的所有必要字段都已填写。以下是所有相应的类,我决定发布 pastebin 链接以获得更好的可读性:

  1. 入口实体: http: //pastebin.com/vp8Ym4wz

  2. 类别实体: http: //pastebin.com/vLMJyxdW

  3. EntryAdmin 类:对不起,不得不在这里发帖,由于声誉问题,我只允许两个链接。由于某种原因,前几行格式不正确,对此也感到抱歉。

namespace S4P\MainBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class EntryAdmin extends Admin {

    protected function configureFormFields(FormMapper $formMapper) {
        $formMapper
            ->add('category', 'entity', array('class' => 'S4PMainBundle:Category', 'property' => 'title'))
            ->add('text', null, array('required' => true))
            ->add('image', 'file', array('required' => false))
            ->add('author', null, array('required' => true))
            ->add('title', null, array('required' => true));
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper) {
        $datagridMapper
            ->add('text')
            ->add('img_name')
            ->add('author')
            ->add('title');
    }

    protected function configureListFields(ListMapper $listMapper) {
        $listMapper
            ->add('text')
            ->add('img_name')
            ->add('author')
            ->add('title');
    }

}

我很感激任何帮助。

问候贝尼

4

3 回答 3

1

使用 Symfony 2.4,我对非必填字段有类似的问题,我不想为空(我想默认为 '' 或 0)。使用 Symfony 表单构建器,如果一个字段不是必需的并且也留空(文本)或默认值(选择),实体字段将填充 NULL 值。文档说您应该在表单字段上添加一个属性empty_data,以指定替代的空数据值应该是什么。

$builder->add('gender', 'choice', array(
     'choices' => array(
         'm' => 'Male',
         'f' => 'Female'
     ),
     'required'    => false,
     'empty_value' => 'Choose your gender',
     'empty_data'  => ''
));

根据文档,这似乎是正确的解决方案。

但不幸的是,到目前为止,这对我也不起作用。我继续收到错误:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'gender' cannot be null

并且查询包含null该字段,因此该属性似乎empty_data没有任何效果。

注意:我的实体将默认值定义为 '' 并且没有 nullable=true。数据库设置为 NOT NULL。所以我看不出这些应该提交为NULL的任何理由。

于 2014-07-16T22:29:35.027 回答
0

由于没有任何效果,我决定从数据库中删除该字段并重新创建它。出于某种原因,这是解决方案。很明显没有魔法这种东西,它一定是我在我的条目实体中监督的东西。无论如何感谢您的帮助。

问候贝尼

于 2013-07-30T13:28:08.783 回答
0

将 nullable=true 添加到任何可以为空的列。您将每个属性映射到表单字段这一事实并不排除该属性以空值结束。

更新注释后,您需要更新数据库架构。

于 2013-07-29T20:26:44.303 回答