【问题标题】:Symfony2 - Updating this form to use AJAXSymfony2 - 更新此表单以使用 AJAX
【发布时间】:2014-10-20 07:29:44
【问题描述】:

由于我还是 Symfony2 的初学者,我一直在广泛搜索——包括简单教程的官方文档或如何将这个简单的表单转换为使用 AJAX 的分步指南,所以我不会必须刷新页面。

有人可以指导我逐步了解 Twig 文件和控制器中的内容以实现这一点吗?

这是 Controller 和 Twig 文件的原始代码:

控制器

/**
 * @Route("/form", name="form")
 */
public function formAction(Request $request)
{
    $article = new Article();

    $form = $this->createForm(new ArticleType(), $article);

    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $em->persist($article);
        $em->flush();

        $session = $request->getSession();
        $session->getFlashBag()->add('message', 'Article saved');

        return $this->redirect($this->generateUrl('formsaved'));
    }

    return $this->render('Form/form.html.twig', array(
        'form' => $form->createView()
    ));
}

/**
 * @Route("/formsaved", name="formsaved")
 */
public function formSavedAction()
{
    return $this->render('Form/formsaved.html.twig');
}

form.html.twig

{% block body %}
    {#{{ form(form) }}#}
        {{ form_start(form) }}
        {{ form_errors(form) }}

        {{ form_row(form.title) }}
        {{ form_row(form.body) }}
    {{ form_end(form) }}
{% endblock %}

formsaved.html.twig

{% block body %}

    {% for flashMessage in app.session.flashbag.get('message') %}
    <p>{{ flashMessage }}</p>
    {% endfor %}

{% endblock %}

文章类型表单

class ArticleType extends AbstractType 
{

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('title', 'text', array(
        'label' => 'Title'
    ))
            ->add('body', 'textarea')
            ->add('save', 'submit');
}

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

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Symfony2\FormBundle\Entity\Article'
    ));
}
}

【问题讨论】:

    标签: ajax forms symfony


    【解决方案1】:

    这更多的是前端而不是后端,所以你应该研究一些jQuery。

    首先,尝试在表单上启动AJAX,并尝试在无效提交时替换它

    来自 google 的第一个教程:http://kb.worldsecuresystems.com/851/cpsid_85119.html

    你还应该研究replaceWith()jQuery函数

    【讨论】:

      【解决方案2】:

      1. jQuery

      .. 假设你知道 jquery

         $('body').on('click','#submitButton',  function(){ 
              //$(".loading").show();
      
              // getting the value of your input using the class (.) or id (#)
              var titleValue = $('#titleInput').val(); 
      
              //POST ajax
              var DATA = 'title=' + titleValue;
      
              $.ajax({
                  type: "POST",
                  // Routing.generate = fosjsroutingbundle You have to install this bundle            (generates routes in js )
                  // or put the route manually, but it's quite dirty
      
                  url: Routing.generate('your_symfony_route'),
                  data: DATA,
                  cache: false,
                  success: function(data){
                      // $(".loading").hide();
                         $(".ajaxResponse").html(data);
      
      
                      }
                  });    
      
          }); 
      

      2。 PHP

      在你的控制器中

      如何从ajax查询中获取数据?

        $request = $this->container->get('request');
      
              // ajax
              if($request->isXmlHttpRequest())
              {
                 $title = $request->request->get('title');
      

      如何持久化数据?

          $myArticle = new Article();
          $myArticle->setTitle($title);
          $em = $this->container->get('doctrine')->getEntityManager();
          $em->persist($myArticle);
          $em->flush();
      

      如何返回响应

          $mesage = new Response("your article was added to databse");
          return $message;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-12
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 2020-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多