我的列表视图显示了现有对象的列表,我展示了一个新的/创建按钮,它带来了创建一个调用控制器的新对象的表单。
我不知道是否有更合适的方法可以做到这一点,但我想出了部分有效的代码。当我的网址是/ new(仅显示表单)时代码有效,但是当它是/ list时它不起作用。
列表视图(仅相关代码):
{# 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>
新观点:
{# AppBundle/Resources/views/new.html.twig #}
{{ form(form) }}
控制器方法:
// 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,
));
}
非常感谢你的时间!!
答案 0 :(得分:0)
list.html.twig中没有数据显示。你必须添加这种代码:
/.../
{% for object in objects %}
{{ object.text }}
{% endfor %}
<div id="info">
<button type="button" onClick="new()">New Object</button>
</div>