Symfony2 で AJAX を実装するのは、私が今見ているようにとても難しいですか?
私の目標は、投稿を作成するためのフォームを表示する 1 ページのアプリケーションを実装することです (各投稿には、投稿のタイトルと投稿の内容があります)。フォームが送信されると、AJAX が div#output のフォームの下に投稿を表示します。
私のテンプレートは次のようになります。
{% extends '::base.html.twig' %}
{% block body %}
<form action="{{ path('post_creates', { 'id': entity.id }) }}" id="form_ajax" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<p>
<input type="submit" value="create" />
</p>
</form>
<ul class="record_actions">
<li>
<a href="{{ path('post') }}">
Back to the list
</a>
</li>
</ul>
<div id="output"></div>
{% endblock %}
{% block javascripts %}
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://jwpsrv.com/library/leLjogZ6EeOBvCIACusDuQ.js"></script>
<script src="{{ asset('bundles/testblog/js/test2.js') }}"></script>
<script>
$("#form_ajax").submit(function(){
tinyMCE.get("test_bundle_blogbundle_posttype_postContent").save();
var content= $("#test_bundle_blogbundle_posttype_postContent").val();
var title = $("#test_bundle_blogbundle_posttype_postTitle").val();
$.ajax({
type: "POST",
url: "{{ path('post_creates', { 'id': entity.id }) }}",
data: {datas:title, date:content},
cache: false,
success: function(data){
$('#output').html(data);
}
});
return false;
});
</script>
{% endblock %}
コントローラーは次のとおりです。
public function createsAction(Request $request, $id)
{
$request = $this->container->get('request');
$entity = new Post();
if($request->isXmlHttpRequest())
{
$title = $request->request->get('datas');
$content = $request->request->get('date');
$em = $this->container->get('doctrine')->getEntityManager();
if($title != '')
{
$entity->setPostContent($content);
$entity->setPostTitle($title);
$id=$entity->getId();
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$post = $em->getRepository('TESTBlogBundle:Post')->find($id);
}
else {
$post = $em->getRepository('TESTBlogBundle:Post')->find($id);
}
$deleteForm = $this->createDeleteForm($id);
return $this->container->get('templating')->renderResponse('TESTBlogBundle:Post:show.html.twig', array(
'entity' => $post, 'id' => $id,
'delete_form' => $deleteForm->createView(),
));
}
else {
return $this->indexAction();
}
}
次の問題があります。
Controller requires that you provide a value for the "$id" argument (because there is no default value or because there is a non optional argument after this one).
コントローラー内の $id を var_dump すると、常に null になります。関数の引数で値を渡すと、コントローラーは正常に動作します。Symfony2 に関する私の知識では、不足しているものを見つけることができません。あなたの助けは本当に感謝しています.