首页 文章

symfony2构建表单实体oneToMany

提问于
浏览
0

我正在学习symfony框架并且有一个大问题 .

我有两个数据库表:category(主键:categoryid)和product(主键:productid和外键:category_categoryid) .

在Controller中添加“editAction”以编辑产品数据(包括字段category_categoryid)并保存在DB中 .

表单必须包含用于对产品进行分类的类别下拉列表 .

代码:

ORM中的关系yml

实体:产品......

manyToOne:
 category:
  targetEntity: Category
   inversedBy: products
   joinColumn:
    name: category_categoryid 
    referencedColumnName: categoryid

实体:类别......

oneToMany:
 products:
  targetEntity: Product
   mappedBy: category

表格/类型ProductType

public function buildForm(FormBuilderInterface $builder, array $options)
{
...

$builder->add('category_categoryid', 'entity',
array('class' => 'SysCatalogoBundle:Category',

'property' => 'name',));

...
}

ProductController的

public function editAction(Request $request)
{
$id = 1;
$em = $this->getDoctrine()->getManager();
$products= $em->getRepository('SysCatalogoBundle:Product')->find($id);
$form = $this->createForm(new ProductType(), $products);


...
}

视图使用元素中的类别列表重新定义表单,但不是选定的产品类别(保存在DB中) . 我证明使用类型“query_builder”但没有工作,也尝试用类“新类别”没有工作eather . 如果我使用更简单的数组(数组(1,2,3))的“选择”类型,则选择类别 .

哪个可能是问题? ORM实体的关系?我按照官方的symfony2文档 .

非常感谢你的帮助! (对不起,我的英文)

2 回答

  • 1

    您没有在表单构建器中使用orm映射 . 尝试将Form / Type ProductType更改为:

    public function buildForm(FormBuilderInterface $builder, array $options) { 
    ...
    
        $builder->add('category', 'entity', array());
    
    ... 
    }
    
  • 1

    我认为这个解决方案在Symfony的官方文档中有很多内容 . http://symfony.com/doc/current/book/doctrine.html#add-mapping-information

相关问题