同一页面上的几个表单

时间:2017-01-04 13:10:00

标签: forms symfony

我正在使用Symfony 3.1

我的问题:当我在同一页面上使用2个表单时,只有第一个表单正常工作

详情

在我的主页上,我有一份联系表格和一份评论表格。 它们不是链接,而是使用不同的实体。

通过两个不同的renderController调用它们。

使用FormBuilder创建表单并通过AJAX提交

我发现他们说使用createNamedBuilder的文章,但仍然无法正常工作。 如果只有一个表单处于活动状态,那么它就可以运如果两者都处于活动状态,则只有第一个有效。 第二个发送POST方法,但不提交表单

我很多天都在寻找解决方案,但仍然没有......请帮助!!!

非常感谢

奥利维亚

view.html.twig



{{ render(controller('BecowoCoreBundle:Workspace:contact', {name: ws.name})) }}


{{ render(controller('BecowoCoreBundle:Booking:bookingList', {name: ws.name})) }}




联络管理员:



public function contactAction($name, Request $request)
      {
        $contact = new Contact();
        // $managerContactForm = $this->createForm(ManagerContactType::class, $contact);
        $managerContactForm = $this->get('form.factory')->createNamedBuilder('manager_contact', ManagerContactType::class, $contact)->getForm();

        $WsService = $this->get('app.workspace');
        $ws = $WsService->getWorkspaceByName($name);
        $wsHasTeamMembers = $WsService->getWsHasTeamMemberByWorkspace($ws);

        $emailManager = [];
        $i = 0;
        if($wsHasTeamMembers == null or $this->container->get( 'kernel' )->getEnvironment() != 'prod')
        {
          $emailManager[0] = 'test@test.com';
        }else{
          foreach ($wsHasTeamMembers as $wsHasTeamMember ) {
            $emailManager[$i] = $wsHasTeamMember->getTeamMember()->getEmail();
            $i ++;
          }
        }
        
          // On vérifie que c'est bien le form de contact manager qui est envoyé
        if ($request->isMethod('POST') && $managerContactForm->handleRequest($request)->isValid() && $request->request->has('manager_contact')) {
          $message = \Swift_Message::newInstance()
              ->setSubject('Becowo - Nouveau message d\'un coworker')
              ->setFrom('test@test.com')
              ->setTo($emailManager) 
              ->setBody(
                  $this->renderView(
                      'CommonViews/Mail/Manager-contact.html.twig',
                      array(
                          'name' => $managerContactForm->get('name')->getData(),
                          'email' => $managerContactForm->get('email')->getData(),
                          'subject' => $managerContactForm->get('subject')->getData(),
                          'message' => $managerContactForm->get('message')->getData()
                      )
                  )
              );

          $this->get('mailer')->send($message);

          $session = $request->getSession();
          $session->set('contactManager', 'ok');

          return $this->redirectToRoute('becowo_core_workspace_contact', array('name' => $name));
        }

        return $this->render('Workspace/manager-contact.html.twig', 
          array('managerContactForm' => $managerContactForm->createView(),
            'name' =>$name));
      }




评论控制器:

public function viewAction(Request $request)
  {
    $WsService = $this->get('app.workspace');
    $ws = $WsService->getWorkspaceByName($request->get('name'));
    $listComments = $WsService->getCommentsByWorkspace($ws);
    $voteAlreadyDone = $WsService->memberAlreadyVoteAndCommentForWorkspace($ws, $this->getUser());

    $comment = new Comment($ws, $this->getUser());
    $formComment = $this->get('form.factory')->createNamedBuilder('comment', CommentType::class, $comment)->getForm();


    if ($request->isMethod('POST') && $formComment->handleRequest($request)->isValid() && $request->request->has('comment'))
    { 
      $em = $this->getDoctrine()->getManager();
      $em->persist($comment);
      $em->flush();

      $this->addFlash('success', 'Merci ! Commentaire et vote bien enregistrés.');

      return $this->redirectToRoute('becowo_comment', array('name' => $request->get('name')));
    }

    return $this->render('Workspace/comments.html.twig', array('formComment' => $formComment->createView(), 'listComments' => $listComments, 'ws' =>$ws, 'voteAlreadyDone' => $voteAlreadyDone));
  }

通过AJAX提交表单:



    // Page d'un WS, envoye le commentaire et le vote en AJAX
    $(function () {
        $("#comment_Envoyer").unbind("click").click(function(){
        	$.ajax(Routing.generate('becowo_comment', {name: document.getElementById('wsName').innerHTML}), {
                data: $('#comment-form').serialize(),
                type: "POST",
                success: function(data) {
                    $('#CommentResults').html(data);
                },
                error: function() {
                	$('#CommentResults').html("Une erreur est survenue, veuillez réessayer plus tard");
                }
            });
        	return false;
        });
    });

    // Page d'un WS, envoye le formulaire de contact manager en AJAX
    $(function () {
        $("#submitContactManager").unbind("click").click(function(){
            $.ajax(Routing.generate('becowo_core_workspace_contact', {name: document.getElementById('wsName').innerHTML}), {
                data: $('#manager-contact-form').serialize(),
                type: "POST",
                success: function(data) {
                    $('#modal-body-manager-contact').html(data);
                },
                error: function() {
                    $('#modal-body-manager-contact').html("Une erreur est survenue, veuillez réessayer plus tard");
                }
            });
            return false;
        });
    });`enter code here`




2 个答案:

答案 0 :(得分:0)

将表单构建为Class。 http://symfony.com/doc/current/forms.html#creating-form-classes

通过

在控制器中创建表单
controller method  $this->createForm(....);

来自Book的例子 公共功能newAction()

{
    $task = ...;
    $form = $this->createForm(TaskType::class, $task);

    // ...
}

注意FORM名称!

public function getName()
    {
        return 'payments';
    } 

您必须在同一页面中为表单添加不同的表单名称!

不要在JQuery中生成路由,只需在Form类或Twig中为表单设置操作,直接从Form执行操作。

在这种情况下你的ajax代码是这样的:

$("#form_id_first, #form_id_second").submit(function (e){
    e.preventDefault();
    $form = $(e.target);
    $ajax($form.attr('action')) {
        ...some: code,
        data: $form.serialize(),

        ...some: code
    }
});

最后 - 不要用于一个表格 - 一个控制器。在一个具有不同名称的控制器中创建多个表单并进行渲染,或者创建Twig Extention,但在同一个地方处理所有表单!

Symfony2 : Two forms in a same page

答案 1 :(得分:0)

非常感谢!!!!!

它正在工作:)

你的JS代码中有2个小错误

$ ajax应为 $ .ajax

我必须添加'输入:" POST"'即使我在控制器中设置了theMethod

如果有人遇到同样的问题,这是完整的代码:

view.html.twig



{{ render(controller('BecowoCoreBundle:Workspace:contact', {name: ws.name})) }}


{{ render(controller('BecowoCoreBundle:Workspace:voteAndComment', {name: ws.name})) }}




workspace Controller(两个表单必须位于同一控制器中,但可以采用不同的操作)



public function contactAction($name, Request $request)
  {
    $contact = new Contact();
    $managerContactForm = $this->get('form.factory')->createNamedBuilder('manager-contact-form', ManagerContactType::class, $contact)
      ->setAction($this->generateUrl('becowo_core_workspace_contact', array('name' => $name)))
      ->setMethod('POST')
      ->getForm();

    $WsService = $this->get('app.workspace');
    $ws = $WsService->getWorkspaceByName($name);
    $wsHasTeamMembers = $WsService->getWsHasTeamMemberByWorkspace($ws);
    
      // On vérifie que c'est bien le form de contact manager qui est envoyé
    if ($request->isMethod('POST') && $managerContactForm->handleRequest($request)->isValid() && $request->request->has('manager-contact-form')) {
      $message = \Swift_Message::newInstance()
          ->setSubject('Becowo - Nouveau message d\'un coworker')
          ->setFrom('contact@becowo.com')
          ->setTo($emailManager) 
          ->setBody(
              $this->renderView(
                  'CommonViews/Mail/Manager-contact.html.twig',
                  array(
                      'name' => $managerContactForm->get('name')->getData(),
                      'email' => $managerContactForm->get('email')->getData(),
                      'subject' => $managerContactForm->get('subject')->getData(),
                      'message' => $managerContactForm->get('message')->getData()
                  )
              )
          );

      $this->get('mailer')->send($message);

      $this->addFlash('success', 'Merci ! Email bien envoyé.');

      return $this->redirectToRoute('becowo_core_workspace_contact', array('name' => $name));
    }

    return $this->render('Workspace/manager-contact.html.twig', 
      array('managerContactForm' => $managerContactForm->createView(),
        'ws' =>$ws));
  }

   public function voteAndCommentAction($name, Request $request)
  {
    $WsService = $this->get('app.workspace');
    $ws = $WsService->getWorkspaceByName($request->get('name'));
    $listComments = $WsService->getCommentsByWorkspace($ws);
    $voteAlreadyDone = $WsService->memberAlreadyVoteAndCommentForWorkspace($ws, $this->getUser());

    // Création du formulaire de commentaires
    $comment = new Comment($ws, $this->getUser());
    $formComment = $this->get('form.factory')->createNamedBuilder('comment-form', CommentType::class, $comment)
      ->setAction($this->generateUrl('becowo_comment', array('name' => $name)))
      ->setMethod('POST')
      ->getForm();


    if ($request->isMethod('POST') && $formComment->handleRequest($request)->isValid() && $request->request->has('comment-form'))
    { 
      $em = $this->getDoctrine()->getManager();
      $em->persist($comment);
      $em->flush();

      $this->addFlash('success', 'Merci ! Commentaire et vote bien enregistrés.');

      return $this->redirectToRoute('becowo_comment', array('name' => $request->get('name')));
    }

    return $this->render('Workspace/comments.html.twig', array('formComment' => $formComment->createView(), 'listComments' => $listComments, 'ws' =>$ws, 'voteAlreadyDone' => $voteAlreadyDone));
  }




通过AJAX提交表单:



$("#manager-contact-form").submit(function (e){
    e.preventDefault();
    $form = $(e.target);
    $.ajax($form.attr('action'), {
        data: $form.serialize(),
        type: "POST",
        success: function(data) { 
          $('#contentToRefresh').html(data);  
        },
        error: function() {
          $('#contentToRefresh').html("Une erreur est survenue, veuillez réessayer plus tard");          
        }
    });
});

$("#comment-form").submit(function (e){
    e.preventDefault();
    $form = $(e.target);
    $.ajax($form.attr('action'), {
        data: $form.serialize(),
        type: "POST",
        success: function(data) {
          $('#CommentResults').html(data);         
        },
        error: function() {
          $('#CommentResults').html("Une erreur est survenue, veuillez réessayer plus tard");
        }
    });
});