duanla8800 2015-10-26 17:34
浏览 42

从不同的角度提交表格

this question may sound a bit newbie. What I am trying to do is to show a form inside a view, create an object and submit it.

My list view shows a list of existing objects and I showed a new/create button that brings the form which creates a new object calling the controller.

I don't know if there is a more proper way to do this but I came up with this code that works partially. The code works when my url is /new (showing only the form), however while it is /list it doesn't work.

List view (only relevant code):

{# AppBundle/Resources/views/list.html.twig #}

<div id="info">
    <button type="button" onClick="new()">New Object</button>
</div>

<script>
    function new() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
          document.getElementById("info").innerHTML = xhttp.responseText;
        }
      }
      xhttp.open("GET", "/new", true);
      xhttp.send();
    }
</script>

New view:

{# AppBundle/Resources/views/new.html.twig #}

{{ form(form) }}

Controller methods:

// AppBundle/Controller/ObjectController

public function newAction(Request $request)
{
    $object = new Object();
        $form = $this->createFormBuilder($object)
        ->add('Text', 'textarea')
        ->add('save', 'submit')
        ->getForm();
    $form->handleRequest($object);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($object);
        $em->flush();
        return $this->redirectToRoute('list');
    }
    return $this->render('AppBundle:new.html.twig', array(
        'form' => $form->createView(),
        ));    
} 

public function listAction(Request $request)
{   
    $objects = $this->getDoctrine()
        ->getRepository('AppBundle\Entity\Object')
        ->findAll();
    return $this->render('AppBundle:list.html.twig', array(
            'objects' => $objects,
        ));    
}

Thanks a lot for your time!!

  • 写回答

1条回答 默认 最新

  • duanliang1999 2015-10-26 17:45
    关注

    No data are displayed in list.html.twig. You have to add this kind of code:

    /.../
    {% for object in objects %}
      {{ object.text }}
    {% endfor %}
    
    <div id="info">
        <button type="button" onClick="new()">New Object</button>
    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line