Symfony2 持久化相关对象

标签 symfony doctrine-orm

这是我的问题: 实体地址簿 1-N 实体编号

Controller 显示带有 AddressBook 及其编号的编辑表单,但是当我保存表单时,出现此错误: fatal error :在非对象上调用成员函数 setTipo()

奇怪的是,数据保存正确

这是我的代码:

 /**
 * Modifica dati Anagrafica
 * @Route("/contatto/{id}/modifica", name="_anagrafica_modifica")
 * @Template()
 */
public function modificaAction($id)
{
    $em = $this->getDoctrine()->getManager();
    $anagrafica = $em->getRepository('MercurioInterfaceBundle:Anagrafica')->find($id);

    if (!$anagrafica) {
        throw $this->createNotFoundException('No anagrafica found for id '.$id);
    }

    $form = $this->createForm(new \Mercurio\InterfaceBundle\Form\Anagrafica\FormAnagrafica(), $anagrafica);

    $request = $this->getRequest();

    if ($request->getMethod() == 'POST')
    {
        $form->bind($request);
        if ($form->isValid())
        {
            $chiave = $request->request->get('anagrafica');

            $em = $this->getDoctrine()->getManager();
            $anagrafica = $em->getRepository('MercurioInterfaceBundle:Anagrafica')->find($id);

            $anagrafica->setNominativo($chiave['nominativo']);
            $anagrafica->setIndirizzo($chiave['indirizzo']);
            $anagrafica->setCap($chiave['cap']);
            $anagrafica->setCitta($chiave['citta']);
            $anagrafica->setNote($chiave['note']);
            $em->flush();

            $dettaglio = $em->getRepository('MercurioInterfaceBundle:AnagDettaglio')->findBy(array('anagrafica_id' => $id,));
            foreach ($chiave['anag_dettagli'] as $d)
            {
                $dettaglio->setTipo($d['tipo']);
                $dettaglio->setValore($d['valore']);
                $dettaglio->setRiferimento($d['riferimento']);
            }
            $em->flush();

            return $this->redirect($this->generateUrl('_anagrafica_contatto', array('id' => $id)));
        }
    }

    return array(
        'form' => $form->createView(),
        'id' => $id
    );
}

最佳答案

已解决:

$form = $this->createForm(new \Mercurio\InterfaceBundle\Form\Anagrafica\FormAnagrafica(),$anagrafica);
if ($request->isMethod('POST')){
  $form->bind($request);

  if ($form->isValid()) {
    $em->persist($anagrafica);
    $em->flush();
    return $this->redirect(....)
  }
}

关于Symfony2 持久化相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14815052/

相关文章:

Symfony:如何从第三方包加载工作流配置

php - Symfony2/Doctrine 中两列的查询生成器和分组依据生成重复项

mysql - 带有 DoctrineExtensions 的 doctrine 2 中的 FIND_IN_SET

symfony - 使用事件监听器创建 preUpdate 或 preFlush 事件

php - Doctrine QueryBuilder 重用部分

php - 2 个表与 Doctrine2 PHP 之间的双重关联

php - Symfony2 Routing.yml 到外部 url

php - KnpMenuBundle - 如何为菜单的每个元素设置图标类?

symfony - JMSSerializerBundle RuntimeException:您必须为 Entity::$field 定义类型

symfony - 为什么教义会更新我表单中的每个对象?